所以,我有一个问题,我不确定如何问。我有一个属性,我在一个指令的控制器中由auth0库(要遵循的代码)设置。我需要从另一个app控制器修改该属性。
具体来说,用例是登录/注销。当用户登录并单击注销按钮时,我可以设置属性的值,而不是问题。但是当他们没有登录并且他们登录时,我无法在登录控制器的指令中设置该属性。
指令:
angular
.module('app')
.directive('loginLogout', loginLogout);
function loginLogout() {
var directive = {
...
scope: {
loggedin: '='
},
controller: loginLogoutController,
controllerAs: 'vm',
bindToController: true
};
return directive;
function loginLogoutController(auth,store,$location,toastr,$parse ) {
var vm = this;
vm.logout = logUserOut;
vm.loggedin = auth.isAuthenticated;
function logUserOut() {
auth.signout();
...
vm.loggedin = false;
}
}
}
登录控制器: (缩写)
function LoginController(auth, store, $location, toastr) {
var vm = this;
vm.login = function () {
auth.signin({}, loginSuccess, loginFailure);
function loginSuccess(profile, token){
...
// ========== I want to set the value of vm.loggedin from the directive here.
}
function loginFailure(){
...
}
};
}
我尝试过像$ parse这样的东西,并设置修补指令配置中的隔离范围。没运气。任何帮助表示赞赏。
答案 0 :(得分:1)
您可以尝试使用$ rootScope。$ broadcast和$ scope。$ on进行此类通信。
您已使用controllerAs来避免注入$ scope。当然,这需要在控制器中注入$ scope。但是在这种特定情况下(即使用controllerAs时)使用$ scope可能不是那么糟糕(https://github.com/toddmotto/angularjs-styleguide)。
Login Controller:
function LoginController(auth, store, $location, toastr) {
var vm = this;
vm.login = function () {
auth.signin({}, loginSuccess, loginFailure);
function loginSuccess(profile, token){
...
// ========== I want to set the value of vm.loggedin from the directive here.
$rootScope.$broadcast('loginCheck');
}
function loginFailure(){
...
}
};
}
指令
function loginLogoutController(auth,store,$location,toastr,$parse ) {
var vm = this;
vm.logout = logUserOut;
vm.loggedin = auth.isAuthenticated;
function logUserOut() {
auth.signout();
...
vm.loggedin = false;
}
$scope.$on('loginCheck', function(event, args) {
// Set vm.loggedin
});
}
答案 1 :(得分:0)
我现在能想到的是,你可以使用angular.js函数绑定。
.directive('loginLogout', loginLogout);
function loginLogout() {
var directive = {
...
scope: {
loggedin: '=',
confirmAction: '&'
},
controller: loginLogoutController,
controllerAs: 'vm',
bindToController: true
};
<!--In html-->
<login-logout confirm-action="doSomething()"> </login-logout>
function LoginController(auth, store, $location, toastr) {
var vm = this;
vm.login = function () {
auth.signin({}, loginSuccess, loginFailure);
function loginSuccess(profile, token){
...
// call doSomething here
doSomething()
}
function loginFailure(){
...
}
};
}