Angularjs 具有独立作用域的指令不会触发 DOM 指令之外的更改

Angularjs Directive with Isolated Scope doesn't trigger DOM change outside of directive

我正在研究 angular 具有独立作用域的指令。 我刚刚遇到了一个有趣的情况。当我从局部作用域调用一个函数时,它改变了 $scope 变量的内容,这不会影响 DOM。在我的示例中,我向 $scope.customers 列表添加了一个新元素,这不会触发 ngRepeat,因此 DOM 的这一部分不会受到应呈现 ngRepeat 项目的位置的影响。

指令代码:

function addItem() {
    scope.add();
        items.push({
        name: 'New Directive Customer'
    });
    scope.$broadcast("refresh");
    render();
}
...
return {
  restrict: 'EA',
  scope: {
      datasource: '=',
      add: '&',
    },
    link: link
};

本地函数代码:

$scope.addCustomer = function() {
    counter++;
    $scope.customers.push({
        name: 'New Customer' + counter,
        street: counter + ' Cedar Point St.'
    });

    alert($scope.customers.length);
};

DOM ng重复部分:

<isolate-scope-with-controller datasource="customers" add="addCustomer()"></isolate-scope-with-controller>
<hr />
<div>
    <ul>
        <li ng-repeat="customer in customers">{{customer.name}}</li>
    </ul>
</div>

alert() 会在每次点击按钮后显示 $scope.customers 变大,但是 ngRepeat 在 DOM 上不起作用。

完整代码: http://plnkr.co/edit/8tUzKbKxK0twJsB6i104

我的问题是,这是否可能以某种方式触发此类指令的 DOM 更改?

提前致谢

你的 plunkr 仅在删除指令的点击回调中对 event.srcElement.id 的检查后才对我有用。

 function addItem() {
      //Call external function passed in with &
      scope.add();

      //Add new customer to the local collection
      items.push({
          name: 'New Directive Customer'
      });


      scope.$broadcast("refresh");
      render();
  }

在控制器中,您必须使用 $scope.$apply 使更改显示在模板中:

    $scope.addCustomer = function() {
      $scope.$apply(function(){
        counter++;
        $scope.customers.push({
          name: 'New Customer' + counter,
          street: counter + ' Cedar Point St.'
        });

    });

http://plnkr.co/edit/lGmGiPIqEm2AA8cngkHz?p=preview