I'm struggling with making a custom directive watch the result of a function that's bound to the scope in the controller.
Here is the HTML. I'm passing the key of the ng-repeat
to the function in the controller in order to determine whether this element should be active or not.
<div ng-repeat="(key, value) in myArray" my-custom-directive element-is-active="elementIsActive(key)">
</div>
This is the part of the code in the controller that matters. Depending on the user's input, this function returns either true or false, indicating whether the element is selected or not.
$scope.elementIsActive = function (key) {
if(key===$scope.selectedElement) {
return true;
}
return false;
}
If the element is active, I want the custom directive to perform its functionality. Here's the custom directive:
myAngularModule.directive('myCustomDirective', function (){
function link (scope, element, attrs) {
scope.$watch(scope.active(), function (){
console.log("triggered");
});
}
return {
link:link,
scope: {
active: "&elementIsActive"
}
}
})
I am encountering difficulties getting the $watch
method to work properly. The message "triggered" appears only once upon loading, and then it seems to stop watching, despite the fact that the output of the function is changing.