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

埃里亚斯

好日子 大家

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

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

Monsteruash

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

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章