Can I watch for changing attributes in directive?
I have something like this:
<online-wathers></online-watchers>
It shows online connected users to the video broadcast and requires a broadcast-id. Obviously without this attribute it won't work. This video broadcast starts not on document ready, but when a publisher actually wants to start it. And when he starts - the backend gives me the broadcast id.
For now I just append it to the DOM with broadcast-id="xx" when api returns me broadcast-id.
$(".online-watchers-container")
.html($("<online-watchers broadcast-id='"+broadcast.id+"' />"));
$(".chat-container")
.html($("<chat broadcast-id='"+broadcast.id+"' />"));
$(".request-container")
.html($("<live-requests broadcast-id='"+broadcast.id+"'></live-requests>"));
// compile directives
angular.bootstrap(angular.element("online-watchers, chat, live-requests"), ['MyApp']);
But is there any internal way to watch adding or changing an attributes? So on page load I will already have <online-watchers></online-watchers> in DOM and when I get response with broadcastId i just add attribute to element in DOM and directive reacts on it.
Please, if you treat it like shit-code, I'll much appreciate if you show some examples of better solution.
Thanks.
Yes, you can
function MyDirective() {
return {
link: function (scope, iElement, iAttrs) {
scope.$watch(iAttrs.scopeProp, function (val) {
console.log("prop: " + val);
});
iAttrs.$observe("interpolated", function (val) {
console.log("interpolate: " + val);
});
}
}
}
.
<my-directive scope-prop="someId" interpolated="{{someId + 1}}"
.
function MyCtrl($scope) {
$scope.someId = 12;
}
For more examples, check out: AngularJS - How to get evaluated attributes inside a custom directive