将对象传递给组件

Ami*_*.io 12 angularjs angularjs-directive angularjs-components

我创建了一个组件,需要引用创建组件的对象.我没有上班,所有的考试都失败了.下面,我试着描述一下这个意图.

组件定义可能如下所示:

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

function MyController(myObject) {
    var vm = this;

    vm.myObject = myObject;
}
Run Code Online (Sandbox Code Playgroud)

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

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

        myObject.ref = "<my-component myObject='{{myObject}}'></my-component>";
        return myObject;
    }
Run Code Online (Sandbox Code Playgroud)

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

任何想法都非常感谢.谢谢.

Ami*_*.io 15

解决方案1

在您的模板中:

<my-component key='$ctrl.myObject'></my-component>
Run Code Online (Sandbox Code Playgroud)

在代码中:

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
}
Run Code Online (Sandbox Code Playgroud)

解决方案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);
}
Run Code Online (Sandbox Code Playgroud)

用法:

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

    myObject.ref = "<my-component key='" + myObject.key + "'></my-component>";
    return myObject;
}
Run Code Online (Sandbox Code Playgroud)