Reputation: 3534
I've created 2 directive one for displaying box(confirmedBox
directive) and one for showing that box (confirmingBox). Inside link function of confirmingBox
, I've created confirmedBox
by compiling with parent scope is confirmingBox
. However, when click on "Show box" button, it log isDisplay undefined
, which means I can't do 2 way binding for variable isDisplay from the parent to child directives. I don't know why it've not worked?
Code live: http://plnkr.co/edit/SHH1JEtGJxibyem25kfd?p=preview
Code javascript:
angular.module('AppA2_Task',[])
.directive('confirmedClick', function ($compile, $rootScope) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.displayBox = true;
element.on('click', function () {
element.attr('disabled', 'disabled');
var boxScope = $rootScope.$new(true, scope);
var boxElem = $compile('<div data-confirming-box data-confirm="confirm" data-is-displayed="displayBox"></div>')(boxScope);
element.append(boxElem);
scope.$apply(function () {
scope.displayBox = true;
});
});
}
}
})
.directive('confirmingBox', function () {
return {
//require: '^confirmedClick',
restrict: 'A',
template: "<div ng-if='isDisplayed'>I am a box</div>",
scope: {
isDisplayed: '='
},
link : function(scope){
console.log('isDisplayed',scope.isDisplayed);
}
}
})
.controller('MainController', function () {
});
Code html
<body data-ng-controller="MainController">
<button data-confirmed-click>Show box</button>
</body>
Upvotes: 0
Views: 153
Reputation: 38490
You are linking the template with boxScope
, but setting displayBox = true
on scope
.
Change it to:
boxScope.displayBox = true;
You also need to do this before compiling and linking, or it will be undefined
when the link function of confirmingBox
executes.
Lastly, either call scope.$apply()
without arguments at the end, or wrap everything in the click function with it.
I prefer the second alterantive since Angular will then internally wrap it in a try...catch
block, and any exceptions that occur will be passed to the $exceptionHandler
service.
Example:
link: function(scope, element, attrs) {
element.on('click', function() {
scope.$apply(function() {
element.attr('disabled', 'disabled');
var boxScope = $rootScope.$new(true, scope);
boxScope.displayBox = true;
var boxElem = $compile('<div data-confirming-box data-confirm="confirm" data-is-displayed="displayBox"></div>')(boxScope);
element.append(boxElem);
});
});
}
Demo: http://plnkr.co/edit/OwcgD0NntVo3DhTVvXmA?p=preview
Upvotes: 1