2017-07-21 27 views
0

这里的目标是让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"; 
 
}); 
 
\t 
 
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>

+0

AngularJS框架不允许在同一元素上有两个隔离范围。另外两个使用模板的指令都不起作用。您如何期待这两个模板能够解决?你想让用户看到什么?你想用这个完成什么? – georgeawg

+0

请参阅[错误:$ compile:multidir for Component Directive with Attribute Directive](https://stackoverflow.com/questions/45196150/error-compilemultidir-for-component-directive-with-attribute-directive/45204883#45204883)for一个修复。 – georgeawg

+0

@georgeawg - 我想要完成的是问题的第一行。你可以摆脱指令中的模板,这只是一个不好的例子。所有指令需要做的是对变化进行验证。 –

回答

0

研究后,我发现角只返回$validators布尔(相对于object)。在这一点上,我决定我的做法是错误的。我决定为每个唯一的错误消息创建一个独特的$valiators。然后使用ng-message作为输出。

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