Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularJS $scope change not updating view

I have been banging my head against an angularJS $scope issue. I have an array that I update in a controller function. According to my console logs, the values inside it are indeed changed. However, the view is not updated. Here are the snippets.

//array initialisation

    $scope.fieldSuggestions = []

//modifying function

  $scope.changeCurrentInput = function(fieldName, eye) {
    for(var field in $scope.test){
      console.log($scope.test[field].name)
      if($scope.test[field].name === fieldName){
        console.log($scope.test[field].values)
        console.log("be4 update")
        console.log($scope.fieldSuggestions)
        $scope.fieldSuggestions = $scope.test[field].values;
        console.log("after update")
        console.log($scope.fieldSuggestions)
      }
    }
  };

//view

 <div ng-repeat="choice in fieldSuggestions">       
    <button class="button button-positive">{{choice}}</button>
</div>

MORE DETAILS...

I think this might be relevant. I have a parent view, and several child views. Each of these routes use the same controller. i.e: the property controller in routes.js is the same for all. The button that calls the modifying function is in the child views, but the ng-repeat that does not get updated is in the parent view.

like image 343
tarball111 Avatar asked Aug 07 '26 16:08

tarball111


2 Answers

Due to fact that you are changing nested properties Angular is not triggering digests. You can simply fix that by adding in link or controller function:

$scope.$watchCollection('fieldSuggestions', function(newFieldSuggestions, oldFieldSuggestions) {
  $scope.fieldSuggestions= newFieldSuggestions;
}); 

Things to point out: That may be not the most optimal for large collections and complex objects.

like image 162
masterspambot Avatar answered Aug 10 '26 06:08

masterspambot


Turns out I was shadowing the parent fieldSuggestions variable by declaring my child controllers as being the same one as the parent. The solution was to not redeclare the controller on the child routes as it sees the parent one automatically.

Thanks everyone who helped.

like image 37
tarball111 Avatar answered Aug 10 '26 06:08

tarball111



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!