Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - model changes not updating the view

AngularJS Classic: Im changing my Model on ng-click an the view is not updating. I thought a simply $scope.$apply() would update but i'm not getting it working. I suppose I'm not setting $apply() in the right place or something like that.

Example: Plunker

The name of the Object is changed on Press button.

like image 861
strangfeld Avatar asked May 18 '26 22:05

strangfeld


1 Answers

Just update your explorerObject one more time after clicking, cause it is still pointing on your previous object:

 $scope.click = function () {
    ExplorerService.setExplorerObject({
      selected : {
        name: 'Defined Now !',
        id: 'id',
        timestamp: 'timestamp'
      },
      templateURL: 'views/beispiel.html'
    });
     $scope.explorerObject = ExplorerService.getExplorerObject(); // <--- here
  }

Working: http://plnkr.co/edit/UWE7o3mtAzY3xzYRWfkf?p=preview

After question' edit:

You can use $watch in your second controller:

app.controller('SecondCtrl', function($scope, ExplorerService) {

  $scope.$watch(function(){
      return ExplorerService.getExplorerObject();
  },function(n,o){
      $scope.explorerObject = ExplorerService.getExplorerObject(); 
  },true)

});

Working: http://plnkr.co/edit/8mZO5kZmTrqwHKnxtBSd?p=preview

Or use a $broadcast approach, like:

app.controller('SecondCtrl', function($scope, ExplorerService) {

  $scope.explorerObject = ExplorerService.getExplorerObject(); 

  $scope.$on("EXPLORER_OBJECT_CHANGED" ,function(event,obj){ 
      $scope.explorerObject = obj;
  });    

});

And in your service add: $rootScope.$broadcast("EXPLORER_OBJECT_CHANGED", explorerObject);

Example: http://plnkr.co/edit/9WKypJTb0wViQZ01m9TN?p=preview

like image 140
Ivan Chernykh Avatar answered May 20 '26 12:05

Ivan Chernykh



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!