P.Brian.Mackey P.Brian.Mackey - 1 year ago 44
AngularJS Question

How can I use isolated scope with a component and a directive?

The goal here is to let

know when there is an error(s) found in the directive. The error must be displayed here:

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

How can I get isolated scope with a directive inside a component? The following application works if you uncomment the 2 lines mentioned below. As it is, I get error:

Multiple Directive Resource Contention

I can read the causes. I need to know how to fix this while still allowing the directive to have isolated scope. I may have 3-4 of these directives on a page and each one needs it's own unique of
that is also available to the parent.

(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;
$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: [
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>

<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>


Answer Source

After researching, I noticed Angular only returns bool from $validators (as opposed to object). At this point I decided my approach was wrong. I decided to create a unique $valiators for each unique error message. Then use ng-message for the output.

In order to work with multiple components on the same page, I also have to check the ngModel.$error as part of validation. This blog covers the basic approach.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download