Reputation: 9151
I'm just starting with Angular and have a quick question:
var data = JSON.parse('[{"name": "Joe","account": "12355845454","rent": "500"}]');
angular.module('ngAppRentManager', []).
controller('RentCtrl', ['$scope', function ($scope) {
$scope.tenants = data;
}]);
setTimeout(function () {
data = JSON.parse('[{"name": "Sara","account": "54874","rent": "600"}]');
console.log("Poke Angular!");
}, 2000);
When my variable data
has changed. How do I tell Angular to update the model?
Upvotes: 1
Views: 1952
Reputation: 1
You can use $scope.$watch
:
$scope.$watch("data", function (newVal, oldVal) {
//your update code
//newVal is your data's changed value
});
Upvotes: 0
Reputation: 9151
I've found a working solution for my problem
var data = JSON.parse('[{"name": "Joe","account": "12355845454","rent": "500"}]');
angular.module('ngAppRentManager', []).
controller('RentCtrl', ['$scope', '$timeout', function ($scope, $timeout) {
$scope.tenants = data;
$scope.getData = function (newData) {
$scope.tenants = newData;
$scope.$apply();
};
}]);
setTimeout(function () {
data = JSON.parse('[{"name": "Sara","account": "54874","rent": "600"}]');
console.log("Poke Angular!");
// Is this the best way to call Angular from outside scope?
angular.element($('#control')).scope().getData(data);
}, 2000);
If this can be improved by calling the controller directly, please let me know.
Upvotes: 0
Reputation: 4151
Use the $timeout
service to stay within angular context.
var data = JSON.parse('[{"name": "Joe","account": "12355845454","rent": "500"}]');
angular.module('ngAppRentManager', []).
controller('RentCtrl', ['$scope', '$timeout', function ($scope, $timeout) {
$scope.tenants = data;
}]);
$timeout(function () {
data = JSON.parse('[{"name": "Sara","account": "54874","rent": "600"}]');
console.log("Poke Angular!");
}, 2000);
Upvotes: 3
Reputation: 7169
ad .apply() to your code like this
var data = JSON.parse('[{"name": "Joe","account": "12355845454","rent": "500"}]');
angular.module('ngAppRentManager', []).
controller('RentCtrl', ['$scope', function ($scope) {
$scope.tenants = data;
setTimeout(function () {
$scope.tenants = JSON.parse('[{"name": "Sara","account": "54874","rent": "600"}]');
console.log("Poke Angular!");
$scope.$apply();
}, 2000);
}]);
http://jsbin.com/tirebavaho/1/
Upvotes: 3