AngularJS 1.5父控制器如何将数据传递给组件控制器
我有一个组件,如:
Check Plunkr Example(更新并使用解决方案:)谢谢) my-component.js声明 (function() { 'use strict'; angular .module('app') .component("myComponent",{ bindings: { obj: "=" },controller: "ComponentController",controllerAs: "vm",template: '<section class="result"><h2>{{vm.title}}</2>' + '<h3>Using the Parent Controller values</h3>' + '<ul><li>{{ vm.obj.a }}</li><li>{{vm.obj.b}}</li></ul>' + '<h3>Using the Children controller values:'+ '<ul class="component-controller"><li>{{ vm.copiedObj.a }}</li><li>{{vm.copiedObj.b}}</li></ul>' + '</section>' }); })(); 我的组件控制器 (function() { 'use strict'; angular .module('app') .controller('ComponentController',ComponentController); function ComponentController() { var vm = this; vm.title = "I'm the Children controller" vm.copiedObj = vm.obj; // This should store the myObj variable located in the MainController } })(); 和父母控制者 (function() { 'use strict'; angular .module('app',[]); })(); // app.controller.js // /////////////////// (function() { 'use strict'; angular .module('app') .controller('MainController',MainController); function MainController() { var vm = this; vm.title = "I'm the Parent controller"; vm.myObj = { a: "I'm the first value",b: "I'm the second value" }; } })(); 所以,如果我有一个类似的模板 <body ng-controller="MainController as vm"> <h2>{{vm.title}}</h2> <my-component obj="vm.myObj"></my-component> </body> 重要的是我有obj =“vm.myObj”的地方吗? 我不想只是将vm.myObj值打印到组件中, 解决方法
我们使用组件的方式是使用bindings属性.它是指令范围和bindToController属性组合的简化版本.
在指令中,scope属性允许我们定义是否要继承或隔离$scope.随着时间的推移,这种选择被推断为合理的默认值,几乎总是使我们的指令具有孤立的范围.通过添加bindToController属性,我们可以定义要传递给隔离范围的属性并直接绑定到控制器. 在组件中,使用bindings属性删除此重复过程,因为默认情况下$scope始终是隔离的. 一般例子: // directive .directive("myDirective",function myDirective() { return { scope: {},// isolate scope bindToController: { value: "=" // two-way binding } }; }); // component .component("myComponent",{ bindings: { value: "=" // two-way binding } }); 详细示例: angular .module("myApp") .controller("MyController",function MyController() { var vm = this; vm.myObj = { a: 1,b: 2 }; }) .component("myComponent",{ bindings: { value: "=" },controller: "MyComponentController",template: "<ul><li>vm.value.a</li><li>vm.value.b</li></ul>" }); 在您的模板中,您可以传递数据,如下所示: <div ng-controller="MyController as vm"> <my-component value="vm.myObj"></my-component> </div> 如上所述,默认情况下,数据绑定到(组件)控制器并可在其中访问. 请注意,我们在这里使用双向绑定.从版本1.5开始提供的另一个附加功能是特定于组件的<表示单向绑定的符号.有关更多信息,请查看official documentation中的“基于组件的应用程序体系结构”部分. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |