To effectively monitor the attribute property in a directive, you can utilize the $observe() method like so:
angular.module('myApp').directive('conversation', function() {
return {
restrict: 'E',
replace: true,
compile: function(tElement, attr) {
attr.$observe('typeId', function(data) {
console.log("Updated data ", data);
}, true);
}
};
});
Note that the use of the 'compile' function is chosen here based on the absence of information regarding models and performance considerations.
If models are present, it is advisable to switch from 'compile' to 'link' or implement 'controller'. To track changes in model properties, employ $watch(), ensuring to remove angular {{}} brackets from the property, as shown below:
<conversation style="height:300px" type="convo" type-id="some_prop"></conversation>
For the corresponding directive code:
angular.module('myApp').directive('conversation', function() {
return {
scope: {
typeId: '=',
},
link: function(scope, elm, attr) {
scope.$watch('typeId', function(newValue, oldValue) {
if (newValue !== oldValue) {
// Proceed with your actions here
console.log("I received the new value! ", newValue);
}
}, true);
}
};
});