1

I have an object outside the AngularJS scope that looks something like:

obj = { isBig : true, name: "John" ... }

it has many parameters and it was created outside the angular scope and it updates outside of angularJS (for example - via ajax call that I make with jQuery).

inside my controller I write:

$scope.obj = obj;

How do I create an event that listens to any of the object's changes and updates the view ? So the event is the objects's changes

Specifically I have a parameter called obj.isAjaxCallFailed = true/false that I use in the view as <div ng-show="obj.isAjaxCallFailed"></div>

It's not working. I tried using $on and I can't figure out any way to do it.

0

1 Answer 1

1

Use $watch() on obj to listen for changes (in your controller):

$scope.$watch(function() {
   return obj;
}, function(value) {
   if(value) {
      $scope.obj = obj;
   }
}, true);

At the place in your code where you create or update obj, you use $rootScope.$apply() to kickoff the watches:

function someCallbackOutsideAngular(data) {
   var $rootScope = angular.injector(['ng']).get('$rootScope');
   $rootScope.$apply(function() {
      obj.someKey = data.someValue;
   });
}

Note: angular.injector(['ng']) should probably set somewhere outside the callback (no need to execute it all the time).

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

2 Comments

'ng' is the name of my controller? my ng-app? or it is a constant that is called 'ng'?
'ng' is the module which contains $rootScope. So in this case, it's a constant. See docs.angularjs.org/api/angular.injector

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.