AngularJs 1.5 – 组件不支持观察者,有什么工作?
我已经将我的自定义指令升级到新的组件方法。我读过该组件不支持观察者。它是否正确?如果是这样,如何检测对象的更改。对于一个基本的例子我有自定义组件myBox它有一个子组件游戏绑定在游戏上。如果游戏组件中有更改游戏,我如何在myBox中显示警告消息?我理解有rxJS方法是可能做到纯粹在角度?我的JS FIDDLE
JS FIDDLE
JS var app = angular.module('myApp',[]); app.controller('mainCtrl',function($scope) { $scope.name = "Tony Danza"; }); app.component("myBox",{ bindings: {},controller: function($element) { var myBox = this; myBox.game = 'World Of warcraft'; //IF myBox.game changes,show alert message 'NAME CHANGE' },controllerAs: 'myBox',templateUrl: "/template",transclude: true }) app.component("game",{ bindings: {game:'='},controller: function($element) { var game = this; },controllerAs: 'game',templateUrl: "/template2" }) HTML <div ng-app="myApp" ng-controller="mainCtrl"> <script type="text/ng-template" id="/template"> <div style='width:40%;border:2px solid black;background-color:yellow'> Your Favourite game is: {{myBox.game}} <game game='myBox.game'></game> </div> </script> <script type="text/ng-template" id="/template2"> <div> </br> Change Game <textarea ng-model='game.game'></textarea> </div> </script> Hi {{name}} <my-box> </my-box> </div><!--end app-->
使用ng-change指令
您可以使用ng-change指令对输入更改做出反应。 <textarea ng-model='game.game' ng-change="game.textChange(game.game)"> </textarea> 并且要将事件传播到父组件,事件处理程序需要作为子组件的属性添加。 <game game='myBox.game' game-change='myBox.gameChange($value)'></game> JS app.component("game",{ bindings: {game:'=',gameChange: '&'},controller: function() { var game = this; game.textChange = function (value) { game.gameChange({$value: value}); }); },templateUrl: "/template2" }); 并在父组件中: myBox.gameChange = function(newValue) { console.log(newValue); }); 这是未来的首选方法。使用$ watch的AngularJS策略不可扩展,因为它是轮询策略。当$ watch监听器的数量达到2000左右时,UI变得缓慢。 Angular 2中的策略是使框架更具反应性,并避免将$ watch放在$ scope上。 使用$ onChanges生命周期钩子 在版本1.5.3中,AngularJS将$ onChanges生命周期钩子添加到$ compile服务。 从文件:
—AngularJS Comprehensive Directive API Reference — Life-cycle hooks $ onChanges钩子用于对组件的外部变化做出反应,单向绑定。 ng-change伪指令用于传递来自ng-model控制器的变化,绑定。 使用$ doCheck生命周期钩子 使用版本1.5.8,AngularJS将$ doCheck生命周期钩子添加到$ compile服务。 从文件:
—AngularJS Comprehensive Directive API Reference — Life-cycle hooks 在服务中使用RxJS
使用RxJS Extensions for Angular建立服务。 app.factory("DataService",function(rx) { var subject = new rx.Subject(); var data = "Initial"; return { set: function set(d){ data = d; subject.onNext(d); },get: function get() { return data; },subscribe: function (o) { return subject.subscribe(o); } }; }); 然后只需订阅更改。 app.controller('displayCtrl',function(DataService) { var $ctrl = this; $ctrl.data = DataService.get(); var subscription = DataService.subscribe(function onNext(d) { $ctrl.data = d; }); this.$onDestroy = function() { subscription.dispose(); }; }); 客户端可以通过DataService.subscribe订阅更改,生产者可以使用DataService.set推送更改。 DEMO on PLNKR。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |