Reputation: 65860
I have below mentioned custom directive for detecting the element's click event.
Directive
.directive('myDir', [
'$document', function ($document) {
return {
restrict: 'A',
scope: true,
link: function (scope, element, attrs) {
scope.IsWizardOpen = false;
element.on('click', function (e) {
scope.$apply(function () {
scope.IsWizardOpen = true;
});
e.stopPropagation(); //stop event from bubbling up to document object
});
}
};
}]);
I have tried to watch the changes of the IsWizardOpen
property inside the controller as shown below.But it's not working ? The value of IsWizardOpen
has been changed when clicked the element (i.e. true
).So can you tell me where's the issue ? Thanks in advance.
Controller
$scope.$watch('IsWizardOpen', function () {
if ($scope.IsWizardOpen) {
//my task
}
});
Html
<div my-dir>
</div>
Upvotes: 0
Views: 902
Reputation: 17064
So primitive values are bound to child scopes when they're assigned, therefore you need to have an object wrapping it. For digging deeper, read this.
I made a fiddle with some slight changes, basically I created a wrapper object in the controller and then your directive updates it:
Controller:
function MyCtrl($scope) {
$scope.wrapper = {};
$scope.$watch(function () {
return $scope.wrapper.IsWizardOpen;
}, function (newVal, oldVal) {
if (newVal) {
alert('watch works');
}
});
}
Directive:
myApp.directive('myDir', [
'$document', function ($document) {
return {
restrict: 'A',
scope: true,
template: '<div>Click Me!</div>',
link: function (scope, element, attrs) {
scope.wrapper.IsWizardOpen = false;
element.on('click', function (e) {
scope.wrapper.IsWizardOpen = true;
scope.$apply();
e.stopPropagation(); //stop event from bubbling up to document object
});
}
};
}]);
Upvotes: 2