AngularJS - how to change the value of ngModel in custom directive?

后端 未结 5 1055
再見小時候
再見小時候 2020-12-23 09:53

Lets take a look to my directive:

angular.module(\'main\').directive(\'datepicker\', [
function() {
    return {
        require: \'?ngModel\',
        link:         


        
5条回答
  •  一生所求
    2020-12-23 10:16

    To work with complex binding expressions you should use the $parse service and the assign method.

    For more information watch this video from ng-conf - it's all about the cool things you can do with the ng-model directive: https://www.youtube.com/watch?v=jVzymluqmg4

    app.directive('datepicker', ['$parse',
        function($parse) {
            return {
                require: '?ngModel',
                link: function(scope, element, attributes, controller) {
                    // $parse works out how to get the value.
                    // This returns a function that returns the result of your ng-model expression.
                    var modelGetter = $parse(attributes['ngModel']);
                    console.log(modelGetter(scope));
    
                    // This returns a function that lets us set the value of the ng-model binding expression:
                    var modelSetter = modelGetter.assign;
    
                    // This is how you can use it to set the value 'bar' on the given scope.
                    modelSetter(scope, 'bar');
    
                    console.log(modelGetter(scope));
                }
            };
        }
    ]);
    

提交回复
热议问题