在指令中访问父数据模型

时间:2014-08-18 09:08:59

标签: angularjs angularjs-directive

我写了一个指令来检查数据列中的double值:

标记

<table>
   <tr data-ng-repeat-start="rowItem in vm.model.data" ...>
      <td>
         <input type="text" data-ng-model="rowItem.ID" data-unique-column="vm.model.data" />
      </td>
      ...
   </tr>
</table>

和指令

(function () {
    'use strict';

    angular.module('app').directive('uniqueColumn', function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function (scope, element, attrs, ngModel) {
                element.on('keyup blur', function () {

                    scope.$eval(attrs.uniqueColumn).forEach(function (item) {
                        // validation logic
                    });
                });
            }
        };
    });
})();

一切正常但我问自己是否有解决方案来访问我的转发器的数据,即vm.model.data,而不将参数传递给指令?

2 个答案:

答案 0 :(得分:0)

因为您没有隔离范围,所以您可以阅读javascript的原型继承。你也许可以从孩子那里访问一个方法,然后查找父母的方法。也许使用$ index作为参数。

答案 1 :(得分:0)

为什么不使用另一个指令来定义unique-column的模型,并将其添加为unique-column指令的依赖项,如下所示:

unique-column-model指令:

app.directive('uniqueColumnModel', function() {
  return {
      restrict: 'A',
      controller: function($scope) {
        // add more logic here if necessary
      },
      link: function (scope, element, attrs, ngModel) {
        // save the value of the uniqueColumnModel as a private var in the scope
        scope.$uniqueColumnModel = scope.$eval(attrs.uniqueColumnModel);
      }
  };
});

unique-column指令:

app.directive('uniqueColumn', function() {
  return {
      restrict: 'A',
      // set the uniqueColumnModel directive as a dependency (^ is to search on parents)
      require: ['ngModel', '^uniqueColumnModel'],
      link: function (scope, element, attrs, ngModel) {
        element.on('keyup blur', function () {
            // use the private $uniqueColumnModel var that was
            // previously saved on the scope
            angular.forEach(scope.$uniqueColumnModel, function(item) {
                // validation logic
            });
        });
      }
  };
});

在HTML上:

<tr ng-repeat="item in model.items" unique-column-model="model.items">
  <td>
    <input type="text" ng-model="item.id" unique-column />
  </td>
</tr>

选中plunker

还有改进的余地,但这个想法就在那里......