3

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.

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

I'm sorry that my example was not exactly representing the problem I have. I've updated it now. Thank you for your answer. Plunker
@strangfeld i'm not very expert in performances , but i think that $scope.$watch is more expensive because seems to me that it is running on every digest cycle it means that ExplorerService.getExplorerObject() will run all the time. On the other hand , $rootScope.$broadcast will run only when setExplorerObject will run, and it makes architecture "less coupled" , so in me eyes this approach is more preferred

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.