简体   繁体   中英

Pass ng-model as argument in directive angualjrs

I am writing a directive in AngularJs and I want to pass ng-model as an argument.

<div class="col-md-7"><time-picker></time-picker></div>

The directive is:

    app.directive('timePicker', function () {
    return {
        restrict: 'E',
        replace: true,
        template: '<input type="text" class="form-control time-picker" ng-model="emp.signin">',
        link: function ($scope, element, form) {
            $(element).timepicker({'timeFormat': 'H:i:s'});
        }
    }
})

It is working fine, and here the ng-model is emp.signin . I want to be able to pass this ng-model dynamically as argument

How is this possible?

You can use

<div class="col-md-7"><time-picker model-value="emp.signin"></time-picker></div>

Angular

app.directive('timePicker', function () {
    return {
        restrict: 'E',
        replace: true,
        template: '<input type="text" class="form-control time-picker"ng-model="modelValue ">',
        scope: {
            modelValue : '=',
        }
        link: function ($scope, element, form) {
            $(element).timepicker({'timeFormat': 'H:i:s'});
        }
    }
})

Explaination

The “=” prefix will create a two-way binding between the parent and directive scope and it'll always expect the attribute value to be the model name which means you cannot provide an expression as the value of attribute mapped to “=” prefix.

For reference: " http://www.undefinednull.com/2014/02/11/mastering-the-scope-of-a-directive-in-angularjs/ "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM