简体   繁体   中英

Check if a sub-view is reloaded; angularjs, ui-router

I am using ui-router in angular js to nest views. A directive in one of my parent views requires to watch if a sub-view is reloaded. Can anyone tell me how would I watch if a sub-view inside a view is reloaded?

Here is my HTML

<body>
  <header myDirective></header>
  <div id="content" ui-view name="bodyContent"></div>
</body>

Directive JS

myApp.directive('myDirective', function(){
return function(scope,element,attr){
    scope.$watch('$viewContentLoaded', function(){
        element.on("click", function(){
            // do something
        });

        element.parent().find('#content').on("click", function(){
            //do something
        })
    });
};
})

Here, the $watch statement only watches the parent view load. What I need to do is to add the event listener for #content everytime the sub view (bodyContent) is changed or reloaded.

I was able to find a solution by making use of State Change Events of angular. Here is how I solved the problem:

So far, I had been watching the $viewContentLoaded variable of the parent view, which wasnt of much help. I had to watch the $viewContentLoaded variable of the child View. So, first I checked for "State Change Success" using scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState )) Here, the variable event is important. It has a targetScope variable which is of our concern. Now all I did was watched the $viewContentLoaded variable of the targetScope and add event listener on that. The code looks like this

myApp.directive('myDirective', function(){
    return function(scope,element,attr){
        scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState){
            event.targetScope.$watch('$viewContentLoaded', function(){
                element.on("click", function(){
                    // do something
                });

                element.parent().find('#content').on("click", function(){
                    //do something
                })
            })

        });
    };
})

I hope others will be benefited by this. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM