javascript - AngularJS How to update nested model in select box using ng-options -
trying update model in sibling controller selection of dropdown box.
<div ng-app="myapp"> <fieldset ng-controller="firstctrl"> firstctrl person: {{selectedperson.last}}<br> <select ng-options="p.first + ' ' + p.last p in people" ng-model="selectedperson"></select> {{ selectedperson }} </fieldset> <div ng-controller="secondctrl"> secondctrl person: {{selectedperson.last}}<br> </div>
i tried several solutions (factory, service) , work quite input fields, not select boxes. made simple fiddle how can achieved in simple yet angular way?
finally, here little trick 2 controller have no parent/child relationship. should pass info 1 controller through $rootscope , $broadcast method.
app.js
var myapp = angular.module('myapp', []); myapp.controller('firstctrl', function ($rootscope,$scope) { $scope.selectedperson = null; $scope.people = [ { id: 1, first: 'john', last: 'rambo', actor: 'silvester' }, { id: 2, first: 'rocky', last: 'balboa', actor: 'silvester' }, { id: 3, first: 'john', last: 'kimble', actor: 'arnold' }, { id: 4, first: 'ben', last: 'richards', actor: 'arnold' } ]; $rootscope.updateperson = function(){ $rootscope.$broadcast('update_secondctrl', $scope.selectedperson); } }); myapp.controller('secondctrl', function ($rootscope,$scope) { $scope.selectedperson = null; $scope.people = [ { id: 1, first: 'john', last: 'rambo', actor: 'silvester' }, { id: 2, first: 'rocky', last: 'balboa', actor: 'silvester' }, { id: 3, first: 'john', last: 'kimble', actor: 'arnold' }, { id: 4, first: 'ben', last: 'richards', actor: 'arnold' } ]; $rootscope.$on("update_secondctrl", function(event, selectedperson) { $scope.selectedperson = selectedperson; }); });
index.html
<div ng-app="myapp"> <fieldset ng-controller="firstctrl"> <select ng-options="p.first + ' ' + p.last p in people" ng-model="selectedperson" ng-change="updateperson()" ></select> </fieldset> <fieldset ng-controller="secondctrl"> <select ng-options="p.first + ' ' + p.last grouping p.actor p in people" ng-model="selectedperson"></select> {{ selectedperson }} </fieldset>
i have update fiddle.
javascript angularjs ng-options
No comments:
Post a Comment