[英]How can I access different $scope in angularJS
I'm trying to manipulate ng-switch in navigation using HomeCtrl from route template login button. 我试图使用导航模板登录按钮中的HomeCtrl来操纵导航中的ng-switch。 can't figure it out how can i access different $scope cleaner way without using rootscope or parent hack.
无法弄清楚我如何在不使用rootscope或父级hack的情况下访问不同的$ scope清洁器方式。 please help.
请帮忙。
<body ng-app="myApp">
<div class="nav" data-ng-controller="HomeCtrl">
<div ng-switch on="loggedin">
<p ng-switch-when="false">please login</p>
<p ng-switch-when="true">Welcome</p>
</div>
</div>
<div class="container" ng-view="">
<!-- partial html -->
<button type="button" ng-click="Login()">Login</button>
<button type="button" ng-click="Logout()">Logout</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script>
angular.module('myApp', []);
angular.module('myApp').controller('HomeCtrl', ['$scope', function($scope) {
$scope.loggedin = false;
$scope.Login = function() {
$scope.loggedin = true;
};
$scope.Logout = function() {
$scope.loggedin = false;
};
}]);
</script>
</body>
Try this one 试试这个
<body ng-app="myApp" data-ng-controller="HomeCtrl">
instead of placing it inside div 而不是将其放在div中
This is a good reason to use Controller as and the vm syntax. 这是使用Controller as和vm语法的一个很好的理由。 You can read up on that here: http://www.johnpapa.net/angularjss-controller-as-and-the-vm-variable/
您可以在这里阅读有关内容: http : //www.johnpapa.net/angularjss-controller-as-and-the-vm-variable/
Try this jsfiddle or updated source below. 试试下面的jsfiddle或更新的源代码。
<body ng-app="myApp">
<div data-ng-controller="HomeCtrl as vm">
<div class="nav">
<div ng-switch on="vm.loggedin">
<p ng-switch-when="false">please login</p>
<p ng-switch-when="true">Welcome</p>
</div>
</div>
<div class="container" ng-view="">
<!-- partial html -->
<button type="button" ng-click="vm.Login()">Login</button>
<button type="button" ng-click="vm.Logout()">Logout</button>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script>
angular.module('myApp', []);
angular.module('myApp').controller('HomeCtrl', [function() {
var vm = this;
vm.loggedin = false;
console.log('hello');
vm.Login = function() {
console.log(vm.loggedin);
vm.loggedin = true;
};
vm.Logout = function() {
console.log(vm.loggedin);
vm.loggedin = false;
};
}]);
</script>
</body>
A Service to maintain the login status and other session data would be a reasonable solution so avoid scope sharing hacks. 维护登录状态和其他会话数据的服务将是一个合理的解决方案,因此避免范围共享黑客。
Just inject the service in whichever scope needs to access it, and maintain state within the service. 只需将服务注入到需要访问它的任何范围内,并维护服务内的状态。
https://docs.angularjs.org/guide/services https://docs.angularjs.org/guide/services
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.