如何将隔离范围与组件和指令一起使用?

时间:2017-07-21 20:06:10

标签: angularjs angular-directive angular-components

这里的目标是让MainCtrl知道指令中发现的错误。必须在此处显示错误:

<div ng-if="errors[0]">Error 1: {{errors[0]}}</div>

如何在组件内部使用指令获取隔离范围?如果取消注释下面提到的2行,以下应用程序将起作用。事实上,我得到错误:

Multiple Directive Resource Contention

我可以阅读原因。我需要知道如何解决这个问题,同时仍允许指令具有隔离范围。我可能在一个页面上有3-4个这样的指令,每个指令都需要它自己唯一的errors,父母也可以使用它。

(working case example on codepen)

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.errors = [false, false];
  $scope.text = "bobby";
});
	
app.directive('testDirective', function(){
  return {
   restrict: 'A',
    scope: {
      errors: '=',
      text: '@'
   },
    link: function($scope, $element, $attr, ngModel) {
      console.log('link fired');
      console.log('errors: ', $scope.errors);
      console.log('scope.text', $scope.text);

      $attr.$observe('text', function (val) {
        if($scope.text === 'bobby'){
          $scope.errors[0] = true;
        }else{
          $scope.errors[0] = false;
        }
      });
    },
   template: '<p>text: {{ text }} </p>'
     + '<p>errors: {{errors}}</p>'
     + '<p><input type="text" ng-model="errors" /></p>'
  };
});


app.component('panel', {
  bindings: {
  },
  template: [
    '<div>',
    '</div>'
  ].join(''),
  controller: function() {
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<section ng-app="app" ng-controller="MainCtrl">
  <h3>Parent Scope</h3>
  <p>errors: {{errors}}</p>
  <input type="text" ng-model="text"></div>
  <div ng-if="errors[0]">Error 1: {{errors[0]}}</div>
  <div ng-if="errors[1]">Error 2: {{errors[1]}}</div>

<!--  UNCOMMENT THE FOLLOWING 2 LINES AND THIS APP WILL WORK
  <h3>Directive by itself</h3>
  <div test-directive text="{{text}}" errors="errors"><div>
  -->
    
  <h3>Directive in component</h3>
  <panel test-directive text="{{text}}" errors="errors"></panel>
  
</section>

1 个答案:

答案 0 :(得分:0)

经过研究,我注意到Angular只返回$validators的bool(而不是object)。在这一点上,我认为我的做法是错误的。我决定为每个唯一的错误消息创建一个唯一的$valiators。然后使用ng-message作为输出。

为了在同一页面上使用多个组件,我还必须检查ngModel.$error作为验证的一部分。 This blog涵盖了基本方法。

相关问题