strangfeld
strangfeld

Reputation: 1067

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.

Upvotes: 3

Views: 4447

Answers (1)

Ivan Chernykh
Ivan Chernykh

Reputation: 42186

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

Upvotes: 3

Related Questions