当ui-router状态改变时运行javascript函数?

时间:2016-03-08 12:40:49

标签: javascript angularjs angular-ui-router

在Angular App中我使用ui-router来处理导航等。 在一个单独的脚本文件中,我有一个像这样的函数;

$(function () {
  function doSomething(){
    if ($('.thisclass').length) {
      $('.thisclass').css({ 'height': someHeight });
    }
  }
});

我的问题是,每当状态改变时,我想运行上面的功能。但是因为它不是任何Angular函数的一部分,所以当我引用它时会出现错误,因为我无法找到它。

我应该做什么,而不是上述?

3 个答案:

答案 0 :(得分:8)

您好,您也可以将 jquery代码添加到您所在州的onEnter:function(),因为每次更改状态并加载控制器时都会执行onEnter。< / p>

示例(登录状态):

.state('login', {
                url: '/login',
                controller: 'LoginCtrl',
                templateUrl: '/assets/modules/login/login.html',
                resolve: {
                    user: ['authService', '$q', function (authService, $q) {
                        if (authService.user) {
                            return $q.reject({authorized: true});
                        }
                    }]
                },
                onEnter: function () {
                    //i hide header tabs, you can add your code here
                    $('.container-fluid').css('display', 'none');
                },
                onExit: function () {
                   //onExit is executed when we leave that state and go to another
                }
            });

希望有所帮助,祝你好运。

答案 1 :(得分:7)

我将如何做。

  

app.js

(function(){
    angular.module('app',[]);

    /* other code like configuration etc */
})();
  

SomeService.js

(function(){    
    angular.module('app');
       .factory('someService',function(){
            return {
                     doSomething: function(){
                        $('.container-fluid').css('display', 'none');
                     }
                 };
       });
})();
  

app.run.js

(function(){
  angular.module('app')
  //Inject your service here
  .run(function($rootScope,someService){ 
    //Look for successful state change.
    //For your ref. on other events.
    //https://github.com/angular-ui/ui-router/wiki#state-change-events
    $rootScope.$on('$stateChangeSuccess', function() {
      //If you don't wanna create the service, you can directly write
      // your function here.
      someService.doSomething();
    });
  })
})();

始终将您的角度代码包装在IIFE中,它将所有内容包装在封闭中并防止泄漏并提供一层安全性。

希望这有帮助!

答案 2 :(得分:1)

如果您是通过$ state.go()控制状态更改的人,您可以修改它:

$state.go('somewhere', { 'place': 'somewhere' }).then(() => {
  // write your function here
});