gpt4 book ai didi

AngularJS 1.5+ 组件不支持观察者,解决方法是什么?

转载 作者:行者123 更新时间:2023-12-02 19:15:38 24 4
gpt4 key购买 nike

我一直在将自定义指令升级到新的 component architecture 。我读到组件不支持观察者。它是否正确?如果是这样,您如何检测对象的变化?对于一个基本示例,我有自定义组件 myBox ,它有一个子组件 game ,并绑定(bind)在 game 上。如果游戏组件中有更改游戏,我如何在 myBox 中显示警报消息?我知道有 rxJS 方法是否可以纯粹以 Angular 来做到这一点?我的JSFiddle

JavaScript

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-->

最佳答案

在没有 Watchers 的情况下编写组件

这个答案概述了在不使用 watchers. 的情况下编写 AngularJS 1.5 组件的五种技术

<小时/>

使用ng-change指令

what alt methods available to observe obj state changes without using watch in preparation for AngularJs2?

您可以使用ng-change指令对输入更改使用react。

<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});
});

},
controllerAs: 'game',
templateUrl: "/template2"
});

在父组件中:

myBox.gameChange = function(newValue) {
console.log(newValue);
});

这是 future 的首选方法。 AngularJS的使用策略$watch不可扩展,因为它是一种轮询策略。当数量$watch听众达到 2000 左右时,UI 变得迟缓。 Angular 2 中的策略是使框架更具 react 性并避免放置 $watch$scope .

<小时/>

使用$onChanges生命周期钩子(Hook)

版本 1.5.3 中,AngularJS 添加了 $onChanges $compile 的生命周期 Hook 服务。

来自文档:

The controller can provide the following methods that act as life-cycle hooks:

  • $onChanges(changesObj) - Called whenever one-way (<) or interpolation (@) 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: ... }. Use this hook to trigger updates within a component such as cloning the bound value to prevent accidental mutation of the outer value.

— AngularJS Comprehensive Directive API Reference -- Life-cycle hooks

$onChanges钩子(Hook)用于对组件的外部更改使用react <单向绑定(bind)。 ng-change指令用于传播 ng-model 的更改组件外部的 Controller &绑定(bind)。

<小时/>

使用$doCheck生命周期钩子(Hook)

版本 1.5.8 中,AngularJS 添加了 $doCheck $compile 的生命周期 Hook 服务。

来自文档:

The controller can provide the following methods that act as life-cycle hooks:

  • $doCheck() - Called on each turn of the digest cycle. Provides an opportunity to detect and act on changes. Any actions that you wish to take in response to the changes that you detect must be invoked from this hook; implementing this has no effect on when $onChanges is called. For example, this hook could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not be detected by Angular's change detector and thus not trigger $onChanges. This hook is invoked with no arguments; if detecting changes, you must store the previous value(s) for comparison to the current values.

— AngularJS Comprehensive Directive API Reference -- Life-cycle hooks

<小时/>

require 进行组件间通信

指令可以require其他指令的 Controller 以实现彼此之间的通信。这可以在组件中通过为 require 提供对象映射来实现。属性(property)。对象键指定属性名称,所需的 Controller (对象值)将在该属性名称下绑定(bind)到所需组件的 Controller 。

app.component('myPane', {
transclude: true,
require: {
tabsCtrl: '^myTabs'
},
bindings: {
title: '@'
},
controller: function() {
this.$onInit = function() {
this.tabsCtrl.addPane(this);
console.log(this);
};
},
templateUrl: 'my-pane.html'
});

有关详细信息,请参阅AngularJS Developer Guide - Intercomponent Communicatation

<小时/>

使用RxJS从服务推送值

What about in a situation where you have a Service that's holding state for example. How could I push changes to that Service, and other random components on the page be aware of such a change? Been struggling with tackling this problem lately

使用 RxJS Extensions for Angular 构建服务.

<script src="//unpkg.com/angular/angular.js"></script>
<script src="//unpkg.com/rx/dist/rx.all.js"></script>
<script src="//unpkg.com/rx-angular/dist/rx.angular.js"></script>
var app = angular.module('myApp', ['rx']);

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 .

关于AngularJS 1.5+ 组件不支持观察者,解决方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35534479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com