siebmanb
siebmanb

Reputation: 807

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

Upvotes: 0

Views: 44

Answers (3)

siebmanb
siebmanb

Reputation: 807

The solution was to use $scope.$parent.results to reference the parent scope.

Upvotes: 1

Subin Sebastian
Subin Sebastian

Reputation: 10997

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?

Upvotes: 0

tymeJV
tymeJV

Reputation: 104795

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

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

Upvotes: 0

Related Questions