Question

What am I doing wrong here? In Angular JS, I am trying to add a ng-model name to a custom directive so it binds with the parent scope. I want it to look something like this:

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

I tried this in the directive but the ng-model name that I want to pass via attribute is not adding that to the template:

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>   ',        


    };
});

What am I doing wrong?

Was it helpful?

Solution

You are missing double quotes around the ng-model in your template:

ng-model=thisNgmodel Should be ng-model="thisNgmodel"

Example of ng-init:

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

Example of passing string to directive: To pass a string variable to your directive use the @ sign.

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

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

Now you will be able to pass a string value to your directive and the value attribute on your input will default in with that text. It makes more sense to bind a property to your text box through ng-model though so you can retrieve its value later. By initializing your ng-model value as seen in the previous example you will achieve the same effect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top