我一直在将自定义指令升级到新的组件架构.我读过组件不支持观察者.它是否正确?如果是这样,您如何检测对象的更改?对于一个基本的例子,我有自定义组件myBox
,它有一个带有游戏绑定的子组件游戏.如果游戏组件中有更改游戏,我如何在myBox中显示警告消息?我明白有rxJS方法是否有可能纯粹在棱角分明?我的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"
})
Run Code Online (Sandbox Code Playgroud)
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'> …
Run Code Online (Sandbox Code Playgroud) angularjs angularjs-directive angularjs-scope angularjs-components angularjs-1.5
我有父组件:
(function () {
angular.module('app.module')
.component('parentComponent', {
templateUrl: 'parent.html',
controllerAs: 'vm',
controller: function ($scope) {
this.$onInit = () => {
$scope.parentData = 'test'
}
})
})()
Run Code Online (Sandbox Code Playgroud)
子组件
(function () {
angular.module('app.module').component('childComponent', {
templateUrl: 'child.html',
controllerAs: 'vm',
controller: function () {
this.$onInit = () => {
}
}
})
})()
Run Code Online (Sandbox Code Playgroud)
父级.html
<child-component></child-component>
Run Code Online (Sandbox Code Playgroud)
孩子.html
<p>{{parentData}}</p>
Run Code Online (Sandbox Code Playgroud)
所以我想访问子组件中的parentData,以便在子组件中显示字符串“test”。我该怎么做?我读过一些有关绑定的内容,但我不知道如何在这个示例中使用它。
感谢您的任何建议。