angularjs - Need help to understand async calls in angular js -


i have main controller , nested controllers within it. in main controller have defined object async query service, , try use object in nested controller. in object in nested controller empty, cause fires before updated in main controller.

as understand, asyncronous query should updates scope after data obtain?

.controller('maincontroller', ['$scope', function($scope) {      $scope.udata = {};     $scope.udatacurrent = {};      $scope.usersdata = usersfactory.getusersdata().query(         function(response) {             $scope.udata = response;             $scope.udatacurrent = $filter('filter')($scope.udata, {'user':$scope.myuser});             $scope.udatacurrent = $scope.udatacurrent[0];         },         function(response) {             $scope.message = "error: "+response.status + " " + response.statustext;     }); })]  .controller('nestedcontroller', ['$scope', function($scope) {     console.log($scope.udatacurrent); // returns empty object }]) 

service:

    .service('usersfactory', ['$resource', 'baseurl', function($resource,baseurl) {          this.getusersdata = function(){             return $resource(baseurl+"/index.php?app=users&format=raw&resource=user",null,  {'update':{method:'put' }});         };      }]) 

you use $scope.$watch.

angular.module("app", [])  .controller("outerctrl", ["$scope", "$timeout", function($scope, $timeout) {    $scope.users = null;        $timeout(function() {      $scope.users = ["john", "jack"];    }, 500);  }]).controller("innerctrl", ["$scope", function($scope) {        $scope.changecount = 0;        // todo: bad practice rely on outer scopes here not enforced    // have outerctrl scope parent scope. in example every    // occurrences of innerctrl embedded in outerctrl in html    $scope.$watch("users", function(newvalue, oldvalue) {      // code runs when users array changed      $scope.changecount++;    });  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.js"></script>    <div ng-app="app">    <div ng-controller="outerctrl">      <div ng-controller="innerctrl">        <div>change count: {{changecount}}</div>        <div>users</div>        <div ng-hide="users"> loading...</div>        <ul>          <li ng-repeat="name in users">{{name}}</li>        </ul>      </div>    </div>  </div>


Comments

Popular posts from this blog

gridview - Yii2 DataPorivider $totalSum for a column -

java - Suppress Jboss version details from HTTP error response -

Sass watch command compiles .scss files before full sftp upload -