我想在下面用ng-include使用ng-switch。問題在於ng-init和整個控制器塊在任何ng-includes變更中重新呈現。ng-include導致控制器塊重新渲染
在login_form.html中,當用戶登錄時,我在LoginCtrl中設置了isLoggedIn = true。但是這會導致下面的完整html重新呈現,這又會導致ng-init。
我該如何避免這個循環?
<div ng-controller="LoginCtrl" ng-init="isLoggedIn = false" class="span4 pull-right">
<div ng-switch on="isLoggedIn">
<div ng-switch-when="false" ng-include src="'login_form.html'"></div>
<div ng-switch-when="true" ng-include src="'profile_links.html'"></div>
</div>
</div>
下面是登錄表單的HTML -
<form class="form-inline">
<input type="text" placeholder="Email" ng-model="userEmail" class="input-small"/>
<input type="password" placeholder="Password" ng-model="userPassword" class="input-small"/>
<button type="submit" ng-click="login(userEmail, userPassword)" class="btn">Sign In</button>
</form>
下面是控制器 -
angularApp.controller('LoginCtrl', function($scope, currentUser){
$scope.loginStatus = function(){
return currentUser.isLoggedIn();
};
/* $scope.$on('login', function(event, args) {
$scope.userName = args.name;
});
$scope.$on('logout', function(event, args) {
$scope.isLoggedIn = false;
});*/
$scope.login = function(email, password){
currentUser.login(email, password);
};
$scope.logout = function(){
currentUser.logout();
};
});
吹的是服務 -
angularApp.factory('currentUser', function($rootScope) {
// Service logic
// ...
//
var allUsers = {"rob[email protected]": {name: "Robert Patterson", role: "Admin", email: "[email protected]", password: "rob"},
"[email protected]":{name: "Steve Sheldon", role: "User", email: "[email protected]", password: "steve"}}
var isUserLoggedIn = false;
// Public API here
return {
login: function(email, password){
var user = allUsers[email];
var storedPass = user.password;
if(storedPass === password){
isUserLoggedIn = true;
return true;
}
else
{
return false;
}
},
logout: function(){
$rootScope.$broadcast('logout');
isUserLoggedIn = false;
},
isLoggedIn: function(){
return isUserLoggedIn;
}
};
});
我想我的答案是解決方案1? – asgoth
@asgoth,好吧,你的小提琴基本上使用瞭解決方案1,但由於附加的控制器還有另一個子範圍。你的「一個控制器」答案基本上使用瞭解決方案3 - 你正在調用父範圍中的函數(由於原型繼承,子範圍可用)來更改父範圍屬性。但是由於父對象的屬性,在那裏也有一些解決方案1 - 您可以在解決方案3中使用基元。下面是[解決方案3的小提琴](http://jsfiddle.net/mrajcok/jNxyE /)在父範圍中使用一個基元。 –
+1爲詳細答案標記。讓我實施您的解決方案,看看它是否能解決問題。 – murtaza52