zatziky zatziky - 5 months ago 173
AngularJS Question

Pass object to component

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 MarkerController(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.

Answer

I solved my issue using component bindings.

Component:

angular
.module('myModule')
.component('myComponent', {
    templateUrl: "template.html",
    controller: [
        'objectService'
        MyController
    ],
    bindings: {
        key: '@'
    }
});
function MarkerController(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;
}

Better solution

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 MarkerController(myObject, objectService) {
    var vm = this;

    vm.myObject.whatever(); // myObject is assigned to 'this' automatically
}
Comments