AngularJS: looping through a list of objects returned by a function -


i have controller data api:

.controller('mydatacontroller', ['$http', function($http) {      pdc = this;     pdc.projects = []      pdc.getdata = function(val) {         return $http.get('../myurl/'+val+"/").then(function(response){             return response.data;         });     };      }]); 

i'm trying loop through response data (a list of object [{"foo":3, "bar":"hey"},{...},...,{...}]), calling getdata every time user changes myvalue. code:

<div ng-controller = "mydatacontroller mdc">     <input type="text" ng-model="myvalue">     <p ng-repeat="mydata in mdc.getdata(myvalue)">{{mydata.foo}}</p> </div> 

...but not work. seems there problem on ng-repeat, how can fix?

here's right way go it:

.controller('mydatacontroller', ['$http', function($http) {     pdc = this;     pdc.projects = [];      pdc.getdata = function(val) {         return $http.get('../myurl/'+val+"/").then(function(response){             pdc.data = response.data;         });     }; }]); 

then update markup follows:

<div ng-controller="mydatacontroller mdc"">     <input type="text" ng-model="myvalue" ng-change="mdc.getdata(myvalue)">     <p ng-repeat="mydata in mdc.data()">{{mydata.foo}}</p> </div> 

why wasn't original code giving expected outcome?

  • at time getdata called, promise data possibly available later. don't data then.

  • returning response.data did, not achieve aim because success function not directly connected getdata.

  • angular updates view when there's change in scope. after data returned request, there's nothing suggest has changed. should make assignment property in scope trigger view update (there other ways achieve that, have said need know). expression "mydatacontroller mdc" adds controller scope, , addition changes in controller object trigger view update.


Comments