bro*_*her 7 javascript angularjs angular-ui-router
在Angular应用程序中我使用ui-router来处理导航等.在一个单独的脚本文件中,我有一个像这样的函数;
$(function () {
function doSomething(){
if ($('.thisclass').length) {
$('.thisclass').css({ 'height': someHeight });
}
}
});
Run Code Online (Sandbox Code Playgroud)
我的问题是,每当状态改变时,我想运行上面的函数.但是因为它不是任何Angular函数的一部分,所以当我引用它时会出现错误,因为我找不到它.
我应该做什么,而不是上述?
您好,您也可以将您的jquery代码添加到onEnter:function()您的状态,就像onEnter每次更改状态并加载控制器时执行的那样.
.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
}
});
Run Code Online (Sandbox Code Playgroud)
希望有所帮助,祝你好运.
我就是这样做的.
app.js
(function(){
angular.module('app',[]);
/* other code like configuration etc */
})();
Run Code Online (Sandbox Code Playgroud)
SomeService.js
(function(){
angular.module('app');
.factory('someService',function(){
return {
doSomething: function(){
$('.container-fluid').css('display', 'none');
}
};
});
})();
Run Code Online (Sandbox Code Playgroud)
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();
});
})
})();
Run Code Online (Sandbox Code Playgroud)
始终将您的角度代码包装在IIFE中,它将所有内容包装在封闭中并防止泄漏并提供一层安全性.
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
8374 次 |
| 最近记录: |