ここでの目標は、ディレクティブにエラーが見つかったときに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>
AngularJSフレームワークでは、同じ要素に2つの分離スコープを使用することはできません。テンプレートを使用した2つのディレクティブも機能しません。 2つのテンプレートがどのように解決すると思いますか?あなたは何を見たいのですか?あなたはこれで何を達成しようとしていますか? – georgeawg
for:属性ディレクティブを使用するコンポーネントディレクティブの[エラー:$ compile:multidir](https://stackoverflow.com/questions/45196150/error-compilemultidir-for-component-directive-with-attribute-directive/45204883#45204883)を参照してください。 1つの修正。 – georgeawg
@georgeawg - 私が達成しようとしていることは、質問の最初の行に示されています。ディレクティブでテンプレートを取り除くことができますが、それは単なる悪い例です。すべての指令は変更の検証です。 –