本文介绍了将对象传递给组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个组件,该组件需要引用为其创建该组件的对象.我没有参加工作,我所有的尝试都失败了.下面,我尝试描述其意图.
I have created a component that needs to have a reference to the object for which the component was created. I didn't make to work and all my trials have failed. Below, I try to describe the intention.
组件定义可能看起来像这样:
The component definition would maybe look like this:
angular
.module('myModule')
.component('myComponent', {
templateUrl: "template.html",
controller: [
MyController
],
bindings: {
myObject: '='
}
});
function MyController(myObject) {
var vm = this;
vm.myObject = myObject;
}
在服务中,我想这样创建我的对象:
In a service I would like to create my object like this:
function createMyObject(args) {
var myObject = {some: data};
myObject.ref = "<my-component myObject='{{myObject}}'></my-component>";
return myObject;
}
问题
如何将数据传递到角度分量标记?我是否必须切换回组件指令才能使其正常工作?
How can I pass data to angular component tag? Do I have to switch back to a component directive to make it work?
任何想法都将不胜感激.谢谢.
Any ideas are greatly appreciated. Thank you.
推荐答案
解决方案1
在您的模板中:
<my-component key='$ctrl.myObject'></my-component>
在代码中:
angular
.module('myModule')
.component('myComponent', {
templateUrl: "template.html",
controller: [
'objectService'
MyController
],
bindings: {
key: '=' // or key: '<' it depends on what binding you need
}
});
function MyController(myObject, objectService) {
var vm = this;
vm.myObject.whatever(); // myObject is assigned to 'this' automatically
}
解决方案2-通过组件绑定
组件:
angular
.module('myModule')
.component('myComponent', {
templateUrl: "template.html",
controller: [
'objectService'
MyController
],
bindings: {
key: '@'
}
});
function MyController(myObject, objectService) {
var vm = this;
vm.myObject = objectService.find(vm.key);
}
用法:
function createMyObject(args) {
var myObject = {key: ..., some: data};
myObject.ref = "<my-component key='" + myObject.key + "'></my-component>";
return myObject;
}
这篇关于将对象传递给组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!