我有一个指令,如下所示:
.directive('gdInputField', function() {
return {
//will only work for elements, not attributes.
restrict: 'E',
template: "<label for='{{name}}'>{{label}}</label><input name='{{key}}' id='{{name}}' type='{{type}}' ng-required='{{required}}' /><p>{{entry.1949113882}}</p>",
scope: {
label: '@label',
name: '@name',
key: "@key",
required: "@required",
type: "@type"
},
};
})
我希望添加使用 @key 设置的值作为输入字段的模型名称。如果我设置ng-model='key'
。我得到的字符串是 @key 作为 ng-model 的内容。
这似乎是结果:
$scope={
someting: @key
}
我想要的是:
$scope={
@key: '';
}
如果用户在输入中写入内容,@key 应该更新。
此外,模型竞价的当前名称是什么或者我如何找到?
最佳答案
按如下方式重写代码
app.directive('gdInputField', function () {
return {
//will only work for elements, not attributes.
restrict: 'E',
template: "<label for='{{name}}'>{{label}}</label><input name='{{inputName}}' ng-model='key' id='{{name}}' type='{{type}}' ng-required='{{required}}' /><p>{{key}}</p>",
link: function (scope, elem, attrs) {
scope.inputName = attrs.key;
},
scope: {
label: '@label',
name: '@name',
key: "=",
required: "@required",
type: "@type"
},
};
});
关键点是 key 应该是双向的才能用作模型。
关于javascript - 将 ng-model 设置为与变量相同的名称而不是引用该变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20608958/