14

我创建了一个组件,该组件需要引用为其创建组件的对象。我没有工作,我所有的试验都失败了。下面,我试着描述一下这个意图。

组件定义可能如下所示:

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

问题

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

任何想法都非常感谢。谢谢你。

4

1 回答 1

16

解决方案 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;
}
于 2016-02-28T13:29:00.720 回答