【问题标题】:Angular directive referencing wrong elementAngular 指令引用了错误的元素
【发布时间】:2014-09-27 23:24:49
【问题描述】:

我有一个问题,我用于 ng 重复中的几个类似元素的指令在调用 keyup 函数时显示错误的元素。

plunker:http://plnkr.co/edit/ARFlsgPdxikpzLScztxU?p=preview

下面是相同的代码:
html

<body ng-app="app">
  <section ng-controller="MainController" ng-repeat="item in list">
    <div ng-repeat="item in list">
      <h3>Item {{$index}}</h3>

      <div class="aliasContainer">
        <input text="text" obj-key="alias" value="{{item.alias}}" ng-keyup="logItem($event, item)">
      </div>

      <div class="nameContainer">
        <input text="text" obj-key="name" value="{{item.name}}" ng-keyup="logItem($event, item)">
      </div>
    </div>
  </section>
  <script src="https://code.angularjs.org/1.2.25/angular.js"></script>
  <script src="script.js"></script>
</body>

js

var app = angular.module('app', []);
app.controller('MainController', ['$scope', function($scope){
  console.log("hello ctrl");
  $scope.list = [
    {name: 'Dick Grayson', alias: 'Nightwing'},
    {name: 'Bruce Wayne', alias: 'Batman'},
    {name: 'Jason Todd', alias: 'Robin'}
  ];
}]);
app.directive('objKey', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      scope.logItem = function($event, item) {
       console.log(element);
      };
    }
  };
});

链接函数表现出的行为是针对每个重复的 div,只有 nameContainer 中的输入通过 keyup 传递(记录元素将显示同一父 div 的 nameContainer 中的输入,即使 aliasContainer 中的输入是触发因素。)

【问题讨论】:

  • 您在 plunkr 中混合了 ng-repeatng-controller。这是固定版本:plnkr.co/edit/ARFlsgPdxikpzLScztxU?p=preview
  • 谢谢。现在可以观察到问题了。
  • 请将其重命名为 AngularJS 而不是 Angular,我将取消投票。

标签: angularjs


【解决方案1】:

要重用您的指令并将其范围与外部范围(控制器)分开,您需要为您的指令添加一个isolate scope

app.directive('objKey', function() {
  return {
    restrict: 'A',
    scope: true,     // << Isolating scope
    link: ....
  }
};

【讨论】:

    【解决方案2】:

    您应该查看指令的范围:https://docs.angularjs.org/guide/directive

    如果你不隔离作用域,你的指令的作用域将与它声明时的作用域相同,在这种情况下它将使用由 ng-repeat 创建的子作用域。

    要解决此问题,只需使用 scope: true 隔离范围

    【讨论】:

      猜你喜欢
      • 2015-06-29
      • 2017-02-08
      • 2019-11-19
      • 1970-01-01
      • 2017-02-02
      • 2017-06-11
      • 2013-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多