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

Update angular directive attribute value from parent controller

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

如果您使用 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.customers 后使用 $scope.$apply() 手动触发摘要。

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