【问题标题】:$watch not executing the first time the value changes$watch 在值第一次更改时不执行
【发布时间】:2015-03-20 01:21:02
【问题描述】:

我有 2 个控制器通过共享服务进行通信,其中一个控制器监视服务上的值以进行更改。但是,它仅在值第二次更改后才起作用 - 这可能是什么原因?

export interface ISharedService {
    value: customObject;
}

class SharedService implements ISharedService {
    value: customObject;
}

export class Controller1 {

    private sharedService : ISharedService;

    constructor(sharedService : ISharedService) {
        this.sharedService = sharedService;
    }

    changeValue(value: customObject) {
        this.sharedService.value = value;
    }

}

export class Controller2 {

    constructor($scope : ng.IScope, sharedService : ISharedService) {
        $scope.$watch(() => sharedService.value, (prev, cur) => {
            if(prev !== cur) {
                alert("WEEEEEE!");
            }
        });
    }

}

当我现在通过调用.changeValue() 函数更改视图中的值时,什么也没有发生。在调用该函数的第二次之后,它突然开始工作。

【问题讨论】:

    标签: javascript angularjs angularjs-scope typescript


    【解决方案1】:

    我实际上采用了您的代码,添加了缺失的部分,它对我有用。

    这是html:

    <div ng-app="myModule">
        <div ng-controller="Controller1 as vm">
            <div>changeCounter={{vm.changeCounter}}</div>
        </div>
        <hr>
        <div ng-controller="Controller2 as vm">
            <div>sharedService.value={{vm.sharedService.value}}</div>       
            <button ng-click="vm.onClick()">Click</button>
        </div>
    </div>
    

    代码如下:

    class SharedService {
        value: string;
    }
    
    class Controller2 {
    
        private sharedService;
        constructor(private sharedService) {
            this.sharedService = sharedService;
        }
    
        onClick():void {
            this.sharedService.value = Math.random();   
        } 
    }
    
    class Controller1 {
        changeCounter = 0;
        constructor($scope, sharedService) {
            $scope.$watch(() => sharedService.value, (prev, cur) => {
                if(prev !== cur) { 
                    this.changeCounter = this.changeCounter + 1;
                }
            });
        }
    
    }
    
    angular.module("myModule", [])
    .service("sharedService", SharedService)
    .controller("Controller1", Controller1)
    .controller("Controller2", Controller2);
    

    【讨论】:

      猜你喜欢
      • 2015-09-03
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      • 2022-09-20
      • 2021-11-06
      相关资源
      最近更新 更多