输入无线电不更新模型

时间:2015-12-26 20:18:36

标签: angularjs angularjs-directive angularjs-scope

我创建了一个使用模板的指令,在使用此指令后,输入type = radio不再更新模型。普通文本类型工作正常。

如何更新模型?

app.directive('advformInput', function($compile) {
        return {
            restrict: 'A',
            priority: 1002,
            transclude: true,
            replace: true,
            template: [
                '<div class="advform-input form-group">',
                '   <label class="advform-lbl">',
                '       <input class="form-control" />',
                '       <div class="helper" ng-show="advformInput">{{ advformInput }}</div>',
                '   </label>',
                '</div>'
            ].join('\n'),
            scope: {
                advformInput: '@'
            },
            link: function ($scope, tElement, tAttrs, $ctrls) {
                var ar = ['type', 'name', 'ng-model', 'value'];
                var block = tElement, inp = tElement.find('input');

                $scope.field = tAttrs.advformInput;

                tElement.removeAttr('advform-input')

                // transfer some attributes to the real input
                _.each(ar, function(val, key){
                    inp.attr(val, block.attr(val))
                    block.removeAttr(val)
                })

                // add the type of the input to the div like a class
                block.addClass('inp-' + inp.attr('type'));

                //$compile(inp)($scope);
            }
        };
    });

2 个答案:

答案 0 :(得分:1)

绑定没有任何问题,我想你正试图通过true&amp; <{1}}指令的false值是问题所在。

让我们深入探讨这个问题。

您的指令隔离范围绑定使用@,这意味着您要使用advformInput: '@'},。但是当你从directive元素传递值时,one way binding值被转换为字符串,而不是将该值的advformInput保持为dataType

同样在这里,如果Boolean(Bool)的advform-input="{{myBoolValue}}"(Bool)作为true(字符串)收到"true",那么false将值从"false"传递给ng-show string 1}}。

因此在您的指令模板中,评估ng-show="someString"指令值在两种情况下都作为scope: { advformInput: '=' //`=` for pass value with two way binding also conserves dataType. }, 传递。这就是为什么@总是如此。

<强>代码

=

所以我的建议是将ng-show绑定转换为ng-show="advformInput == 'true'" 以保存参数类型,同时将其传递给指令。

如果您真的关心指令的单向绑定,那么您需要更改someMethod()指令表达式,如下所示。

3

答案 1 :(得分:1)

找到解决方案。
错误是我没有将Type和NgModel放在指令的范围内 我自己删除并添加属性。
不知道如何正确使用范围。

这个问题在SO中帮助了我:

How do I properly build an AngularJS labeled radio input directive?

相关问题