gpt4 book ai didi

angularjs - 将对象传递给组件

转载 作者:行者123 更新时间:2023-12-02 09:11:51 25 4
gpt4 key购买 nike

我创建了一个组件,该组件需要引用为其创建组件的对象。我没能去上类,所有的尝试都失败了。下面,我尝试描述一下其意图。

组件定义可能如下所示:

angular
.module('myModule')
.component('myComponent', {
templateUrl: "template.html",
controller: [
MyController
],
bindings: {
myObject: '='
}
});

function MyController(myObject) {
var vm = this;

vm.myObject = myObject;
}

在服务中我想创建这样的对象:

function createMyObject(args) {
var myObject = {some: data};

myObject.ref = "<my-component myObject='{{myObject}}'></my-component>";
return myObject;
}

问题

如何将数据传递到 Angular 组件标签?我是否必须切换回组件指令才能使其正常工作?

任何想法都将不胜感激。谢谢。

最佳答案

解决方案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 - 通过组件绑定(bind)

组件:

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

关于angularjs - 将对象传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35681636/

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