vcardillo
vcardillo

Reputation: 1696

Update angular model outside of the controller

I'm working through the Angular tutorial, and doing a lot of reading. However, I am having trouble finding an answer to this question. Or, I might be thinking about it incorrectly, which I'm hoping someone can help me out with!

Very simple example:

var phones = [
    {"name": "Nexus S",
     "snippet": "Fast just got faster with Nexus S.",
     "age": 0},
    {"name": "Motorola XOOM™ with Wi-Fi",
     "snippet": "The Next, Next Generation tablet.",
     "age": 1},
    {"name": "MOTOROLA XOOM™",
     "snippet": "The Next, Next Generation tablet.",
     "age": 2}
];

function PhoneListCtrl($scope) {
  $scope.phones = phones;
  $scope.orderProp = 'age';
}

What I have represented above is a source of data that will come from outside of this controller. I have an existing caching function that will XHR the server as necessary for new data.

Let's say that the model then changes:

phones[3] = {"name": "Something new from the server",
         "snippet": "Here is some new incoming data",
         "age": 5};

How do I tell the Angular PhoneListCtrl controller that the model has updated? If you test this yourself and update the array, Angular is not aware of the change, and therefore does not update the DOM.

I'm aware of the $http service, but in my current architecture it is not an option for me to use $http within the controller to obtain the data--the controller needs to be asking an external function that I have written for the data, and I need some way of telling Angular's controller when the data subsequently changes.

Help and insight are appreciated!

Upvotes: 4

Views: 8254

Answers (1)

Chandermani
Chandermani

Reputation: 42669

If you are updating the data from outside angular context, you can get the scope for element where controller is defined, using something like

angular.element(domElement).scope()

and then use

$apply method defined on the scope to push updates

See more details here

Upvotes: 7

Related Questions