简体   繁体   中英

How can i use ng-model with directive in angular js

I have this directive to increment and decrement variable like this

angular.module('shopping')
    .directive('myDir', function () {
        return {
            restrict: 'AE',
            scope: {
                dirModel: '='
            },
            template: '<div><button ng-click="decrement()">-</button>' +
                '<div ng-model="dirModel">{{ value }}</div>' +
                '<button ng-click="increment()">+</button></div>',
            link: function (scope, iElement, iAttrs) {
                scope.increment = function () {
                    scope.value += 20;
                }
                scope.decrement = function () {
                    scope.value -= 20;
                }
            }
        };
    });

I am using like this

<my-dir dirModel="user.interval"></my-dir>

Now when i click on edit form where my scope already have user.interval = 30 then that does not get set.

For new form it works ok

working: http://plnkr.co/edit/jjIgVA?p=preview

Things you are doing wrong:

  • in the view you need to set the dirModel as dir-model

  • in the directive you need to wait for dirModel to compile and then set it to scope.value (you never declare it, you may trying to use ng-model in the div incorrectly)

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

return {
    restrict: 'AE',
    scope: {
      dirModel: '='
    },
    template: '<div><button ng-click="decrement()">-</button><div>{{ value }}</div><button ng-click="increment()">+</button></div>',
    link: function (scope, iElement, iAttrs) {
      scope.increment = function () {
          scope.value += 20;
      }
      scope.decrement = function () {
          scope.value -= 20;
      }

      // wait for variable to compile, set it to your value
      var watcher = scope.$watch('dirModel', function() {
        if(scope.dirModel === undefined) return;
        scope.value = scope.dirModel;
        watcher();
      });
    }
  };

});

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