祝大家日安!
我正在开发一个网络应用,使用typescript和Angular 1.5;
我创建了一个指令,其主要目标是监视用户是否登录,并隐藏/显示相应的元素。
这是链接函数代码:
interface ShowAuthedScope extends ng.IScope{
User: UserService,
_$log: ng.ILogService
}
function ShowAuthedDirective(User:UserService, $log:ng.ILogService) {
'ngInject';
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.User = User;
scope._$log = $log;
scope.$watch('User.current', function (val) {
scope._$log.log('updated!:', val);
})
}
}
}
我的案例的模型是当前用户,根据他是否登录来设置或取消设置。
这是UserService的剪辑代码:
interface UserInterface {
current:GoogleUser;
signIn(options?:SignInOptions):Promise<any>;
signOut():Promise<void>;
}
class UserService implements UserInterface {
public current:GoogleUser;
private _GoogleAuth:GoogleAuthService;
private _AppConstants;
constructor(GoogleAuth:GoogleAuthService, AppConstants) {
'ngInject';
this._GoogleAuth = GoogleAuth;
this._AppConstants = AppConstants;
this.current = null;
}
public signIn(options?:SignInOptions) {
let promise:Promise<any>;
let _options:SignInOptions = options || {};
_options.app_package_name = this._AppConstants.appPackageName;
if (this.current) {
promise = this.current.signIn(_options);
} else {
promise = this._GoogleAuth.signIn(_options);
}
promise = promise.then((googleUser:GoogleUser) => this.current = googleUser);
return promise;
}
public signOut() {
this.current = null;
return this._GoogleAuth.signOut();
}
}
$watch内部的函数在初始化后仅触发一次;
另请注意,我已经尝试传递 true 作为 $watch 函数的第三个参数
希望得到您的帮助!谢谢!
最佳答案
当您从控制台调用 signIn
和 signOut
时,它发生在称为“摘要周期”的外部。 Angular 在每个摘要周期中运行 $watch 语句,但需要发生一些事情来触发它。
例如 ng-click
和所有 Angular 事件处理程序都会自动触发摘要周期,以便可以检测到变量更改。
总而言之,如果您想从控制台执行所有操作,则需要自己触发摘要周期:
angular.element(document).injector().get('$rootScope').$digest()
关于javascript - AngularJS 1.5 : scope. $watch 内部链接函数不会在模型更改时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38333321/