将Ng模型值传递给指令 [英] Passing An Ng-Model Value to A Directive

查看:61
本文介绍了将Ng模型值传递给指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过以前的答案,但是我不确定它们是否是我需要的答案.

I've looked at the previous answers, but I'm not sure if they are the answer I need or not.

我有一条指令,我们称它为"selectValue".一个值可以有一个默认值,我们称它为"$ scope.default".

I have a directive, let's call it "selectValue". A value can have a default, let's call it "$scope.default".

该指令在一个地方看起来像这样:

The directive will look like this in one place:

<select-value ng-model="data.input" controlId="inputSelector" />

但是在另一个地方看起来像这样:

But it will look like this in another:

<select-value ng-model="myValue" controlId="inputSelector" />

我无法选择使ng-model输入相同.它们在不同的地方使用,这是一个遗留代码库.

I do not have the option of making the ng-model inputs the same; they are used in different places and this is a legacy code base.

这是指令的定义:

    .directive('selectValue', ['$timeout', function($timeout) {

    const directive = {
        restrict: 'E',
        scope: {
            controlId: '@',  
            model: '=?'
        },
        controller: 'selectValueCtrl',
        template: '<input id="{{controlId}}" name="{{controlId}}" placeholder="Enter Value" type="text" ng-model="model" />'
    };

    return directive;
}

问题:如何在< select-value> 的"model"属性中输入不同的输入以使其能够访问不同的范围变量?

The question: what do I do to be able to enter different inputs in the "model" attribute of the <select-value> to have it access different scope variables?

所引用的重复"问题是指为ng-click设置值,而不是在表单控件中引用ng-model.

the referenced "duplicate" question refers to setting a value for ng-click, not referencing ng-model in a form control.

推荐答案

据我所知,似乎您正在尝试传递带有预设值的默认值.您面临的问题是您的select-value元素正在使用ng-model指令来尝试传递数据,但是您在指令中的绑定是"model".

From what I can tell, it looks as though you are trying to pass defaults with preset values. The problem you are facing is your select-value element is using the ng-model directive in an attempt to pass the data however your binding in your directive is 'model'.

为了解决此问题,只需将' ng-model '更改为' model ',然后绑定就可以工作了.

In order to fix this issue, simply change the 'ng-model' to 'model' and your bindings should then work.

最后,您的元素应如下所示:

In the end, your element should look like so:

<select-value model="myValue" controlId="inputSelector" />

相对于:

<select-value ng-model="myValue" controlId="inputSelector" />

这篇关于将Ng模型值传递给指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆