繁体   English   中英

AngularJS 1.5:scope。$ watch内部链接函数不会在模型更改时更新

[英]AngularJS 1.5: scope.$watch inside link function doesn't update on model change

好日子 大家

我正在开发一个使用打字稿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函数的第三个参数传递

希望对您有所帮助! 谢谢!

当你打电话signInsignOut从控制台,它发生之外的东西称为“消化周期”。 Angular在每个摘要循环中运行$ watch语句,但是需要发生一些触发它的事情。

例如ng-click和所有Angular事件处理程序会自动触发摘要循环,以便可以检测到变量更改。

因此,总而言之,如果要从控制台执行所有操作,则需要自己触发摘要循环:

angular.element(document).injector().get('$rootScope').$digest()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM