Make sure to include a watcher in the first directive's link
function.
scope.$watch('thingToWatchForRefershing', function (newValue, oldValue) {
if (!newValue || angular.equals(newValue, oldValue)) {
return;
}
scope.$emit('somethingChangedInFirstDirective', dataToBePassed);
});
In your second directive, create a render function that will update models and views when called, and also add a listener.
link: function () {
scope.render = function () {
// insert all necessary logic here
};
scope.$on('somethingChangedInFirstDirective', function (ev, data) {
// re-render everything, essentially reloading the directive
scope.render();
});
// initial rendering
scope.render();
}
Hopefully, this explanation is clear enough for you :)
Additional Instructions:
- Only pass an attribute to the first directive using syntax like:
<custom-carousel data-is-to-be-watched="isToBeWatched" />
, and then set it in the controller: $scope.isToBeWatched = true
. For the second directive, use: <custom-carousel data-is-tobe-reloaded="isToBeReloaded" />
, and initialize it as false in the controller: $scope.isToBeReloaded = false;
- If it's an isolated directive with its own scope, include:
scope:{isToBeWatched: '=?', isToBeReloaded: '=?'}, link: function (...) {...}
- After the directive loads, check
if (scope.isToBeWatched)
. If true, emit an event that will be listened to in the controller. Upon receiving the event, set $scope.isToBeReloaded = true;
, which will affect the variable in the second directive's scope since we passed it there.
- Create a watcher for
isToBeReloaded
and reload the render function as previously described.
Sample code snippets:
Controller:
$scope.isToBeWatched = true;
$scope.isToBeReloaded = false;
$scope.$on('somethingChangedInFirstDirective', function () {
$scope.isToBeReloaded = true;
});
Directive:
scope: {
isToBeWatched: '=?',
isToBeReloaded: '=?'
},
link: function (scope) {
scope.render = function () {
if (scope.isToBeWatched) {
scope.$emit('somethingChangedInFirstDirective');
}
};
scope.render();
scope.$watch('isToBeReloaded', function (newValue, oldValue) {
if (!newValue || angular.equals(newValue, oldValue))
return;
scope.render();
})
}