我可以将组件创建为属性吗?

时间:2017-11-16 18:27:08

标签: javascript angularjs

我正在尝试创建一个组件,该组件将使用父组件注册自己,并在调用父更新时为其提供特定于该子组件的信息。

父:

    angular
    .module('app')
    .component('parentComponent', {
        templateUrl: function ($attrs) {
            return '/Components/Component/template.cshtml';
        },
        bindings: {
            api: "=",
        },
        controller: controller
    });

function controller() {
    var vm = this;
    vm.subscribedApis = [];

    vm.$onInit = function () {
        vm.api.register = register;
        vm.api.update = update;
        vm.api.performOperation = performOperation;
    };

    function update() {
        vm.subscribedApis.forEach(function (api) {
            api.update();
        });
    }

    function register(api) {
        vm.subscribedApis.push(api);
    }

    function performOperation(viewValue){
        //do something given the childs value
    }

子:

    angular
    .module('app')
    .component('childComponent', {
        require: ['^parentComponent', 'ngModel'],
        bindings: {
            parentApi: "<",
        },
        link: function (scope, element, attrs, controller) {
            controller.getViewValue = function () {
                return ngModel.$viewValue;
            }
        },
        controller: childController
    });

function childController() {
    var vm = this;
    vm.$onInit = function () {
        vm.api = {};
        vm.api.update = update;
        vm.parentApi.register(vm.api);
        update();
    };
    function update() {
        var tag = filterTagApi.performOperation(vm.getViewValue());
    }

我的问题是我希望像这样使用子标签

<input type="text" id="title" class="form-control input-sm"
       ng-model="search.parameters.title" autofocus
       child-component parent-api="parentApi" />

<select class="form-control input-sm" ng-model="search.parameters.typeId"
        ng-options="lookup.id as lookup.lookupValue for lookup in lookups.typesOfSomething"
        child-component parent-api="parentApi">
    <option value="" selected>All</option>
</select>

这可能与我可以附加到包含ng模型的不同元素的通用子组件有关,还是我需要找到不同的方法?

1 个答案:

答案 0 :(得分:0)

找到我的答案。组件限制为元素,不允许用作属性。如果我希望它作为属性可用,我将不得不将它作为指令。

来源:https://docs.angularjs.org/guide/component#creating-and-configuring-a-component