简体   繁体   中英

Issue with AngularJS scope in controller

Below is the code of my view and an abstract of code in my controller.

View:

<div id="search_results" ng-controller="SearchCtrl">
   <ul>
      <li ng-repeat="result in results">{{result.name}}</li>
   </ul>
</div>

Controller:

   myapp.controller('SearchCtrl', function($scope,SearchF) {    
      $scope.launch_search = function() {
         SearchF.update(function() {
            $scope.results = SearchF.get();
         });
      }
   })

The function .get() returns my data, but the view does not update. Looks like my scope ($scope.results) does not refer to the general scope. If I write the .update() block outside of the launch_search function, the view updates fine.

Any idea?

Thanks a lot everyone

.get() is an async call, if it's using ngResource , assign the data in the callback:

 SearchF.get({}, function(data) {
     $scope.results = data;
 });

解决方案是使用$scope.$parent.results来引用父作用域。

Off course some one has to trigger your function right ?

put a button with ng-click="launch_search()" , on click of that your view updates. In case you want the view to be updated on load check out

How to execute angular controller function on page load?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM