[英]AngularJS 1.5: scope.$watch inside link function doesn't update on model change
Good day to everyone ! 好日子给 大家 !
I'm developing a web app , using typescript and angular 1.5 ; 我正在开发一个使用打字稿和angular 1.5的网络应用程序 ;
I've created a directive the main goal of wich is to spy on whether user logged in or not, and hide/show corresponding element. 我创建了一个指令 ,该指令的主要目标是监视用户是否登录,以及隐藏/显示相应的元素。
Here is the link function code : 这是链接功能 代码 :
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);
})
}
}
}
The model for my case is the current user, that being set or unset depending on whether he is logged in or not. 我的案例的模型是当前用户,根据用户是否登录来设置或取消设置该模型。
here is the clipped code for the UserService : 这是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();
}
}
The function inside $watch gets triggered only once after initializing; $ watch内部的函数在初始化后仅触发一次;
Also note, that I already tried to pass true as the third parameter of the $watch function 还要注意,我已经尝试将true作为$ watch函数的第三个参数传递
Hope for your help! 希望对您有所帮助! Thanks!
谢谢!
When you call signIn
and signOut
from the console, it happens outside something called a "Digest Cycle". 当你打电话
signIn
和signOut
从控制台,它发生之外的东西称为“消化周期”。 Angular runs $watch statements in every digest cycle, but there needs to happen something that triggers it. Angular在每个摘要循环中运行$ watch语句,但是需要发生一些触发它的事情。
For example ng-click
and all Angular event handlers automatically trigger digest cycle so that variable changes can be detected. 例如
ng-click
和所有Angular事件处理程序会自动触发摘要循环,以便可以检测到变量更改。
So in summary, if you want to do everything from the Console, you need to trigger digest cycle yourself: 因此,总而言之,如果要从控制台执行所有操作,则需要自己触发摘要循环:
angular.element(document).injector().get('$rootScope').$digest()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.