我有一个像这样的Angular指令:
angular.module("app", ["customers"]).run();
angular.module("app").controller("appController", function($scope) {
$scope.customers = [{ name: "Microsoft" }];
setTimeout(function() {
console.log("timeout");
$scope.customers = [{ name: "Apple" }];
}, 1500);
});
angular.module("customers", []).directive("customerList", function() {
return {
restrict: "E",
template:
'<ul><li ng-repeat="customer in vm.customers">{{customer.name}}</li></ul>',
scope: {
customers: "=customers"
},
bindToController: true,
controller: customerListController,
controllerAs: "vm"
};
});
angular
.module("customers")
.controller("customerListController", customerListController);
customerListController.$inject = ["$scope"];
function customerListController($scope) {
const vm = this;
$scope.$watch('vm.customers', function(newValue) {
console.log(newValue)
})
}
我的HTML看起来像这样:
<div ng-app="app" ng-controller="appController">
<customer-list customers="customers"></customer-list>
</div>
我想要实现的是更新appController
中的客户列表并在指令内更新,以便我的列表在1500毫秒后显示Apple
。
答案 0 :(得分:0)
如果您使用setTimeout
Angular不知道您对$scope.customers
所做的更改。使用$timeout
服务,该服务将在超时后自动触发范围摘要:
.controller("appController", function($scope, $timeout) {
$scope.customers = [{ name: "Microsoft" }];
$timeout(function() {
console.log("timeout");
$scope.customers = [{ name: "Apple" }];
}, 1500);
});
使用setTimeout
后,您需要在为$scope.$apply()
分配新值后,使用$scope.customers
手动触发摘要。