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

时间:2017-03-28 11:33:53

标签: javascript angularjs

在以下代码中:

 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 - 未从父组件传递的数据?一个例子可能很有用。

请分享您对如何操作的想法。

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

1 个答案:

答案 0 :(得分:0)

引用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');
  }
);