Pass object to component

两盒软妹~` 提交于 2021-01-26 19:48:35

问题


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

Question

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:


Solution 1

In your template:

<my-component key='$ctrl.myObject'></my-component>

In code:

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
}

Solution 2 - via Component Bindings

Component:

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

Usage:

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

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


来源:https://stackoverflow.com/questions/35681636/pass-object-to-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!