如何将ng-model添加到自定义指令?

时间:2014-03-18 19:47:24

标签: javascript angularjs angularjs-directive angular-ngmodel

我在这里做错了什么?在Angular JS中,我试图将ng-model名称添加到自定义指令中,以便它与父作用域绑定。我希望它看起来像这样:

   <div use-date-picker this-ngmodel="something"></div>
    The ng model: {{ something }}

我在指令中尝试了这个,但我想通过属性传递的ng-model名称没有将它添加到模板中:

app.directive('useDatePicker', function() { 

    return {
        restrict: 'A',
        replace:true,
        scope: {
            thisNgmodel: '=',
            //bindAttr: '='
        },      
        template: '<div class="input-group">' +
                    '<input type="text" class="form-control" datepicker-popup="{{format}}" name="dt" ng-model=thisNgmodel is-open="datepickers.dt" datepicker-options="dateOptions" ng-required="true" close-text="Close" />' +
                    '<span class="input-group-btn">' +
                        '<button class="btn btn-default" ng-click="open($event,\'dt\')"><i class="glyphicon glyphicon-calendar"></i></button>' +
                    '</span>' +
                   '</div>   ',        


    };
});

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您在模板中的ng-model周围缺少双引号:

ng-model=thisNgmodel应为ng-model="thisNgmodel"

ng-init的例子:

<div use-date-picker ng-init="something = 1" this-ngmodel="something"></div>

将字符串传递给指令的示例: 要将字符串变量传递给指令,请使用@符号。

<div use-date-picker string-var="test"></div>

scope: {
    stringVar: '@'
},
template: '<input type="text" value="{{stringVar}}" />'

现在,您可以将字符串值传递给指令,输入中的value属性将默认使用该文本。通过ng-model将属性绑定到文本框更有意义,但您可以稍后检索其值。通过初始化ng-model值,如上例所示,您将获得相同的效果。

相关问题