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



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

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

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

多指令资源争用

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

(代码笔上的工作案例示例(

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>

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

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

最新更新