Faizuddin Mohammed Faizuddin Mohammed - 3 months ago 8
AngularJS Question

How to watch for $scope changes in a directive?

I have a directive like this:

app.directive('selectedForm', function(MainService) {
return {
scope: {
formName: '=currentForm'
},
restrict: 'E',
link: function($scope, iElm, iAttrs, controller) {
$scope.$watch('formName', function(oldV, newV) {
console.log(iElm);
if (someCondition) {
MainService.getForm($scope.formName).then(function(re) {
iElm.html(re);
});
}
});
}
};
});


But, the problem is I cannot watch for changes. I have a
<select>
element in DOM that changes the value of
currentForm
usign
ngModel
. But, even though I select an option, the
watch
function is not working. Am I missing something?

rD. rD.
Answer

You cannot use the same $watch in angular directive in the same way like you use in angular controller. Instead, change it to something like this:

change your html select element to something like this:

<select model="selectedElements">
    ...
    ...
</select>

and inside your directive, change your $watch to:

...
link: function($scope, iElm, iAttrs, controller) {
            $scope.$watch('iAttrs.model', function(oldV, newV) {
...

See also: Is it ok watch the scope inside a custom directive?


EDIT:

The code in your case to watch the value of <select ng-model='currentForm'> ... </select> would be:

...
link: function($scope, iElm, iAttrs, controller) {
            $scope.$watch('iAttrs.currentForm', function(oldV, newV) {
...