javascript - How to watch a child component data not coming from a parent component (Angularjs 1.5 or 1.6)? -
in following codes:
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 name undefined clear greeting if (!this.name) { this.greeting = '' } }; $scope.$watch('$scope.origin', function() { console.log("i here"); }) } });
modified post: use $scope.$watch monitor change of $scope.origin. wrong did do? please try plunker: https://plnkr.co/edit/ddzethqiji4fjnyhpqaj?p=preview
original post: problem common problem using angular 1.5 or 1.6 components, surprisingly, can not find question/answer relating this.
in case, $ctrl.origin not data parent component while $ctrl.name passed child component parent component.
to understanding: $onchanges function can watch $ctrl.name - data coming component external source e.g parent component.
my question: how watch change of local data of component $ctrl.origin - data not passed parent component? example might useful.
please share thoughts on how it.
here plunker: https://plnkr.co/edit/ddzethqiji4fjnyhpqaj?p=info
quoting angularjs:
$onchanges(changesobj) - called whenever one-way bindings updated. changesobj hash keys names of bound properties have changed, , values object of form { currentvalue, previousvalue, isfirstchange() }. use hook trigger updates within component such cloning bound value prevent accidental mutation of outer value.
so first make sure bindings one-way , bindings exist (yours doesn't in case, $onchanges won't work).
as watching variables other scopes, believe $watch capable:
$scope.$watch( () => { // old variable value; }, '$ctrl.origin' => { console.log('something changed on variable', variable-name, 'blah'); } );
Comments
Post a Comment