Pass object to component Pass object to component angularjs angularjs

Pass object to component


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