带隔离作用域的Angularjs指令不会触发指令外的DOM更改

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

本文关键字:指令 更改 DOM 隔离 作用域 Angularjs      更新时间:2023-09-26

我正在用孤立的作用域玩angular指令。我刚刚遇到了一个有趣的情况。当我从局部作用域调用一个函数时,它改变了$scope变量的内容,这不会影响DOM。在我的示例中,我向$作用域添加了一个新元素。这不会触发ngRepeat,所以应该呈现ngRepeat项的DOM的这部分不受影响。

指令代码:

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注释部分:

<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变化从这种类型的指令以某种方式?

Thanks in advance

您的plunkr仅在删除指令的点击回调中的event. srelement .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。

    $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 =预览