angularjs - Angular JS - Parent view not updating when scope changes -
i'm building simple angular test app , have run problem. have list of items , "add item" link @ bottom of list (the list stored on simple nodejs server). "add item" link loads child view lets user set name of new item. when user clicks done item added list on server, tells parent list update. in console can see data being passed parent view isn't reflecting new list of items. i've looked $scope.$apply never using third party library have no reason use (i have tried , gives error "$digest running" seems expected after looking @ docs). here's code in question:
html parent list
<ul data-ng-controller="listcntrl"> <li data-ng-repeat="item in items"> <a href="#/item/{{item.name}}">{{item.name}}</a> </li> <li><a href="#/new">add item</a></li> </ul> <div data-ui-view></div> <!--child view loaded here-->
html child view
<div data-ng-controller="newitemcntrl"> <input type="text" data-ng-model="name"></input> <a data-ng-click="additem()">done</a> </div>
controllers
app.controller('listcntrl',function($scope, listfactory){ listfactory.getitems().success(function(data){ $scope.items = data; }); $scope.update = function(){ listfactory.getitems().success(function(data){ console.log(data); //the correct list in data $scope.items = data; //this doesn't cause view update! }); } }); app.controller('newitemcntrl',function($scope){ $scope.additem = function(){ $http({ method: 'post', url: '/additem', data: json.stringify( {name: $scope.name} ), headers: {'content-type': 'application/json'}, }) .success(function(){ $scope.$parent.update(); }); } });
factory
app.factory('listfactory', function($http){ return { getitems: function(){ return $http({ method: 'post', url: '/getitems', headers: {'content-type': 'application/json'} }); } } });
everything works on server side , in update() function prints out updated list, somehow $scope.items assignment isn't causing list view update. if refresh page list appears correctly. doing wrong here? i'm guessing it's problem understanding of $scope.$parent can't seem figure out. help!
the 'listcntrl' controller on element, while 'newitemctrl' bound child view of data-ui-view, sibling of element, not child.
thus, scope created in newitemctrl not have scope created listcntrl in parent chain.
try this:
<div data-ng-controller="listcntrl"> <ul> <li data-ng-repeat="item in items"> <a href="#/item/{{item.name}}">{{item.name}}</a> </li> <li><a href="#/new">add item</a></li> </ul> <div data-ui-view></div> <!--child view loaded here--> </div>
btw, don't need use $scope.$parent in case. child scopes (but not isolated scopes) have prototypical inheritance parents, i.e. scope.__proto__ === scope.$parent
. using $scope.update() should suffice, long no directive between scope , parent scope defined update function made isolated scope.
Comments
Post a Comment