2
我有一个接受数组的指令。它最初是未定义的,然后在某个时间点被异步定义。
该指令类似于
function XYZDirective() {
return {
restrict: 'EA',
replace: true,
scope: {
array: '='
},
controller: ['$scope', $scope => {
$scope.$watch(() => $scope.array, (newValue, oldValue) => {
$scope.firstElement = (newValue && newValue.length > 0)
? newValue[0]
: null;
});
}],
templateUrl: URL
};
}
这工作得很好。我想然后摆脱$watch
并使用简单的绑定。
function XYZDirective() {
return {
restrict: 'EA',
replace: true,
scope: {
array: '='
},
controller: ['$scope', $scope => {
$scope.getFirstElement = function() {
return ($scope.array && $scope.array.length > 0) ? $scope.array[0] : null;
}
$scope.firstElement = $scope.getFirstElement();
}],
templateUrl: URL
};
}
我希望$scope.firstElement
得到重新评估每一次$scope.array
变化。
然而,这是行不通的。如果我在$scope.array
添加一个观察者,我可以看到它被更新,但变化不会传播到$scope.firstElement