如何观察不是来自父组件(Angularjs 1.5 或 1.6)的子组件数据?



在以下代码中:

var app = angular.module('app', [])
// navigation template
app.component('onChanges', {
bindings: {
name: '<'
},
template: '<h1>{{$ctrl.greeting}}</h1><br><h2>{{origin}}</h2> ',
controller: function($scope) {
$scope.origin = 'international';
this.$onChanges = function(obj) {
if (obj.name && this.name) {
var prefix;
(obj.name.currentValue.toLowerCase() === 'thomas') ?
prefix = 'Howdy ': prefix = 'Hello ';
this.greeting = prefix + this.name;
(prefix === 'Hello ' || !prefix) ? $scope.origin = 'american': $scope.origin = 'australian';
}
// if the name is undefined clear greeting
if (!this.name) {
this.greeting = ''
}
};
$scope.$watch('$scope.origin', function() {
console.log("I am here");
})
}
});

修改后的帖子:我使用 $scope.$watch 来监控 $scope.origin 的变化。我做错了什么? 请尝试此Plunker:https://plnkr.co/edit/DDZeTHQIji4FJnyhpQAJ?p=preview

原文:对于使用 Angular 1.5 或 1.6 组件的人来说,我的问题是一个常见问题,但令人惊讶的是,我找不到与此相关的 SO 问题/答案。

在这种情况下,$ctrl.origin 不是来自父组件的数据,而 $ctrl.name 从父组件传递到子组件。

据我了解: $onChanges函数只能监视 $ctrl.name - 从外部源(例如父组件)进入组件的数据。

我的问题:如何观察组件(如 $ctrl.origin - 不是从父组件传递的数据)的本地数据的变化?一个示例可能很有用。

请分享您对如何做到这一点的想法。

这是我的普伦克:https://plnkr.co/edit/DDZeTHQIji4FJnyhpQAJ?p=info

引用AngularJS:

$onChanges(changesObj) - Called whenever one-way bindings are updated. The
changesObj is a hash whose keys are the names of the bound properties that
have changed, and the values are an object of the form { currentValue,
previousValue, isFirstChange() }. Use this hook to trigger updates within 
a component such as cloning the bound value to prevent accidental mutation 
of the outer value.

因此,首先确保您的绑定是单向的并且绑定存在(在这种情况下您的绑定不存在,因此$onChanges不起作用)。

至于观察其他范围的变量,我相信$watch有能力:

$scope.$watch(
() => { // Old variable value; },
'$ctrl.origin' => {
console.log('something changed on variable', variable-name, 'blah');
}
);

最新更新