gpt4 book ai didi

javascript - 从 Angular 中的指令观察 Controller 的属性

转载 作者:行者123 更新时间:2023-12-04 00:46:14 25 4
gpt4 key购买 nike

我正在尝试从链接函数中的关联指令中观察 Controller 的属性。 Controller 本身使用 controllerAs 设置为 $scope 上的 'window' 对象;这是指令定义:

function windowDirective() {
return {
transclude: true,
template: template,
restrict: 'E',
controller: WindowCtrl,
controllerAs: 'window',
link: function($scope, $element, $attrs, $ctrl) {
$scope.$watch('window.x', function(newValue, oldValue) {
// access x here
});
}
};
}

这里是 WindowCtrl

'use strict';
class WindowCtrl {
move(x, y) {
this.x = x;
this.y = y;
}
}

module.exports = WindowCtrl;

move(x, y) 当我拖动子指令时被调用 - 它肯定被调用并且 this.xthis.y 肯定是在 WindowCtrl 上设置。此外,如果我 console.dir $scope 然后触发 move() 几次,我可以在 chrome 中打开范围(因为它是惰性评估的)并看到 $scope.window.x$scope.window.y 确实被设置了。

但是,除了最初检测到 window.x 未定义时,我的 $scope.$watch 从未实际触发过。不太确定如何进行。我确实搜索并尝试了我找到的所有解决方案,但似乎没有一个有效。

我使用的是 Angular 1.3.16。

注意:对 WindowCtrl.move() 的访问只能从 Angular 的摘要循环中进行 - 见下文 - 但是使用 $scope.$apply() 可以解决这个问题.我不确定为什么会这样。你能解释一下吗?以下是嵌套在上述指令内部的指令。它将调用 onDrag 处的方法,在我的示例中它指向 window.move(x, y);

function windowHeaderDirective() {
return {
transclude: true,
template: template,
replace: true,
require: `^${windowDirective.$name}`,
scope: {
enableClose: '=actionClose',
draggable: '=',
onDrag: '&'
},
bindToController: true,
link: function($scope, $element, $attrs, $ctrl) {
$scope.close = $ctrl.close.bind($ctrl);
let moving = false;
$element.on('mousemove', function(event) {
if(!moving) return
const { x, y } = event;
$scope.header.onDrag({ x, y });
// $scope.$apply here will fix this issue, but why? Isn't $element.on within angular's digest cycle??
});
$element.on('mousedown', function(event) {
moving = true;
});
$element.on('mouseup', function(event) {
moving = false
});
},
controller: controller,
controllerAs: 'header'
};
}

最佳答案

在 $watch 中尝试使用这样的函数观察器:

$scope.$watch(function() {
return $scope.window.x
}, ...

关于javascript - 从 Angular 中的指令观察 Controller 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30914410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com