从父控制器更新角度指令属性值

时间:2018-01-17 21:26:12

标签: angularjs angularjs-directive angular-directive

我有一个像这样的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>

Here's a pen of it

我想要实现的是更新appController中的客户列表并在指令内更新,以便我的列表在1500毫秒后显示Apple

1 个答案:

答案 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手动触发摘要。

演示: https://codepen.io/anon/pen/OzaVRb?editors=1010