Angularjs 使用Angular JS的自定义指令
在我的html中,我像这样包含了我的指令Angularjs 使用Angular JS的自定义指令,angularjs,angularjs-directive,Angularjs,Angularjs Directive,在我的html中,我像这样包含了我的指令 <login ng-show="!authService.authenticated"></login> 登录服务和身份验证通过AuthService工作正常,但问题是一旦成功登录,我仍然无法隐藏登录html集。请有人帮我解决这个问题 谢谢 使用$rootScope而不是$scope.authService angular.module('XXXXX').directive("login", function () { retu
<login ng-show="!authService.authenticated"></login>
登录服务和身份验证通过AuthService工作正常,但问题是一旦成功登录,我仍然无法隐藏登录html集。请有人帮我解决这个问题
谢谢 使用$rootScope而不是$scope.authService
angular.module('XXXXX').directive("login", function () {
return {
restrict: "E",
scope: {
authenticated: '='
},
transclude: true,
replace: false,
templateUrl: "views/layouts/login.html",
controller: function ($scope,$rootScope, AuthService) {
$rootScope.authService = AuthService;
$rootScope.authService.authenticated = false;
$rootScope.authService.authenticated = AuthService.isAuthenticated();
$scope.login = function () {
var username = angular.element.find("[name='username']"),
password = angular.element.find("[name='password']"),
results = null;
username = $(username).val();
password = $(password).val();
results = AuthService.login(username, password);
if (results.status != "failed"){
$rootScope.authService.authenticated = true;
}
};
console.log($rootScope.authService.authenticated);
},
link: function (scope) {
}
}
})) 当您在隔离作用域中声明
authenticated
变量时,您应该通过从directive属性传递该作用域变量来修改该变量,然后您可以轻松地在directive controller中使用authenticated
变量,当用户获得授权时使authenticated
为true,否则将为false
标记
<login authenticated="authenticated" ng-show="!authenticated"></login>
您应该将console.log放在它末尾的scope.login=函数{}中。还可以打印出results.status是什么。你确定它在if(results.status!=“failed”)中吗?你能添加
isAuthenticated
方法的代码吗。它将进入结果中。状态!=想到的“失败”选项:1)将isAuthenticed
标志添加到根作用域2)从指令访问父作用域3)将ng显示放在模板的根元素上,或4)在directive@RuchiraChamara污染$rootScope
不是一个好方法。即使它可以工作,以这种方式使用$rootScope
是一种不好的做法。我认为这将有助于通过检查此rootScope值来验证整个项目中的用户是否已通过身份验证,进一步检查用户是否存在在任何项目中都不需要验证controller@Ruchira查马拉:有帮助吗?
<login authenticated="authenticated" ng-show="!authenticated"></login>
angular.module('XXXXX').directive("login", function () {
return {
restrict: "E",
scope: {
authenticated: '='
},
transclude: true,
replace: false,
templateUrl: "views/layouts/login.html",
controller: function ($scope, AuthService) {
$scope.authService = AuthService;
$scope.authService.authenticated = false;
$scope.authenticated = AuthService.isAuthenticated();
$scope.login = function () {
var username = angular.element.find("[name='username']"),
password = angular.element.find("[name='password']"),
results = null;
username = $(username).val();
password = $(password).val();
results = AuthService.login(username, password);
if (results.status != "failed"){
$scope.authenticated = true;
}
};
console.log($scope.authenticated);
},
link: function (scope) {
}
}
});