我刚刚开始使用Angular,并提出了一个简单的问题:
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);
我的变量data
发生了变化。如何告诉Angular更新模型?
答案 0 :(得分:3)
将.apply()添加到您的代码中
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);
}]);
答案 1 :(得分:3)
使用$timeout
服务保持在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);
答案 2 :(得分:0)
我找到了解决问题的有效方法
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);
如果可以通过直接致电控制器来改善这一点,请告诉我。
<强> Fiddle 强>
答案 3 :(得分:0)
您可以使用$scope.$watch
:
$scope.$watch("data", function (newVal, oldVal) {
//your update code
//newVal is your data's changed value
});