【问题标题】:Having trouble with $watch in Angular controller在 Angular 控制器中遇到 $watch 问题
【发布时间】:2015-03-06 16:10:37
【问题描述】:

我在测试控制器时无法让 $watch 工作。

这里的想法是 ctrl.value 可以以 ARI 格式或 AEP 格式显示,但底层的 $scope.model 始终是 ARI 格式。因此,每当 ctrl.value 更改时,$scope.model 要么只是设置为相同的值,要么转换为 ARI 格式并设置为该值。但是,当 ctrl.value 更改时,我无法触发 $watch。

控制器的相关位如下所示。 (我在手表中使用了函数,所以我可以在测试中监视它们):

   .controller('EventLikelihoodController', function($scope) {

    var ctrl = this;
    ctrl.value = $scope.model;
    ctrl.renderingARI = true;

    ctrl.getValue = function() {
        return ctrl.value;
    };
    ctrl.updateModel = function(newValue) {
        if (ctrl.renderingARI) {
            $scope.model = newValue;
        } else {
            $scope.model = ctrl.convertAepToAri(newValue);
        }
    };
    $scope.$watch(ctrl.getValue, ctrl.updateModel);

});

还有我的茉莉花测试:

    it('sets the model value correctly', function () {

    spyOn(controller, 'updateModel').andCallThrough();
    spyOn(controller, 'getValue').andCallThrough();

    controller.value = 2;
    scope.$digest();

    expect(controller.getValue).toHaveBeenCalled();
    expect(controller.updateModel).toHaveBeenCalledWith(2);
    expect(scope.model).toBe(2);

    controller.switchRendering();
    scope.$digest();

    expect(controller.updateModel).toHaveBeenCalledWith(4);
    expect(scope.model).toBe(4);

});

测试失败,说它预期所有的间谍函数都已被调用,但事实并非如此。

切换渲染函数将值从 ARI 渲染更改为 AEP 渲染。我有其他测试可以验证它是否正常工作(即 ctrl.value 正在改变)。

我不确定问题是实际的 watch 语句,还是只是在测试中运行它的问题(我还没有编写足够的代码来检查控制器是否在测试之外工作...... )

【问题讨论】:

  • 你的手表应该是这个$scope.$watch(ctrl.getValue(), ctrl.updateModel());

标签: javascript angularjs karma-jasmine


【解决方案1】:

我认为您的 watch 语句应该如下所述,因为函数内的 this 不是指您的控制器的 this。让我们手动绑定它

   $scope.$watch(angular.bind(this,ctrl.getValue), ctrl.updateModel);

另外,在 updateModel() 中,我们正在更新 $scope.model,我们正在监听 value 中的变化。 this.value 必须在 updateModel() 中更新。 (这仅适用于应该更改ctrl.value值的方法

【讨论】:

  • 我不这么认为——Angular Docs 中的示例传入函数而不是函数调用。不过,我确实尝试过,以防万一,得到了相同的结果。
  • @velocipede 这里是一个 jsfiddle 演示相同的 jsfiddle.net/divm/nrfc212c
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
相关资源
最近更新 更多