anuj trehan anuj trehan - 1 year ago 157
AngularJS Question

refresh/reload angularjs custom directive

I am using carousel ( in an ionic project. This is a custom angularjs directive. I am using 2 carousels in one screen. Now, what I want is that on change of 1st carousel the second carousel should also get updated with the new value. And to do this the 2nd carousel custom directive has to be reloaded/refreshed. Is there a way to refresh/reload custom directives in angularjs?

Answer Source

Add a watcher in first directive in link function.

scope.$watch('thingToWatchForRefershing', function (newValue, oldValue) {
    if (!newValue || angular.equals(newValue, oldValue)) {
    scope.$emit('somethingChangedInFirstDirective', dataToBePassed);

Now, in your second directive, have a render function which when called will refresh the models and views and also add a listener.

link: function () {
    scope.render = function () {
        // all logic goes here
    scope.$on('somethingChangedInFirstDirective', function (ev, data) {
        // render everything again i.e. reload the directive
    // first time rendering

Hope it helps :)


  1. Pass an attribute to the first directive only. eg: <custom-carousel data-is-to-be-watched="isToBeWatched" /> and in your controller set: $scope.isToBeWatched = true. Also, for the second directive use: <custom-carousel data-is-tobe-reloaded="isToBeReloaded" /> and in the same controller initialize: $scope.isToBeReloaded = false;
  2. If its an isolated directive, having its own scope, then: have this scope:{isToBeWatched: '=?', isToBeReloaded: '=?'}, link: function (...) {...}
  3. Once the directive is loaded, check if (scope.isToBeWatched), is true, it means first directive is loaded/changed since we passed the attr only in first directive. Now, emit an event, which will be listened in the controller. In the listener do: $scope.isToBeReloaded = true; which in turn will set the variable isToBeReloaded in the second directive's scope, since we passed in 2nd directive.
  4. Have a watcher for isToBeReloaded and reload the render fn as I mentioned earlier.

Rough code:


$scope.isToBeWatched = true;
$scope.isToBeReloaded = false;

$scope.$on('somethingChangedInFirstDirective', function () {
    $scope.isToBeReloaded = true;


scope: {
isToBeWatched: '=?',
isToBeReloaded: '=?'
 link: function (scope) {
 scope.render = function () {
    if (scope.isToBeWatched) {

scope.$watch('isToBeReloaded', function (newValue, oldValue) {
    if (!newValue || angular.equals(newValue, oldValue) {return; })

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download