指令中的属性与控制器1的值不同

时间:2017-06-30 13:17:26

标签: javascript angularjs angularjs-directive

控制器:

 constructor($scope) {
            this.$scope = $scope;
            this.counter = 0;
            this.playerCells = [];
            this.$scope.$watch(() => this.playerCells, this.updateCounter(), true)

        }

updateCounter() {
    return () => {
        this.counter = 0;
        this.playerCells.forEach((item) => {
            if ( item.isShip === true ) {
                this.counter++;
                console.log("Ctrl counter "+this.counter)
            }
        })
    }
}

指令

export function fieldDir() {
    return {
        restrict: 'E',
        template: require(...),
        scope: {
            cells: '=',
            counter: '=',
        },
        link: function($scope) {
            $scope.selectShip = function(item) {
                if ( item.isShip === false) {
                    item.isShip = true;
                } else {
                    item.isShip = false;
                }
                console.log("Dir counter " + $scope.counter)

            }
        }
    }
}

<field-dir cells="vm.playerCells" counter="vm.counter"></field-dir>

我在控制器和指令中寻找计数器的值。在第一次触发$ watch后,console.log返回以下值:

Directive log: Dir counter 0
Controller log: Ctrl counter 1

我猜测该指令首先由console.log顺序实例化,并在this.counter触发侦听器功能之前取$watch的初始值。

我有什么方法可以解决这个问题,还是有更好的替代方案来解决我现在所做的事情?

0 个答案:

没有答案