1

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

2
  • can you make a jsfiddle or something like that ?? Commented Nov 25, 2014 at 5:46
  • This is incorrect <div ng-model="dirModel">. ng-model attribute should be on an input element (including selects and textareas), not a div Commented Nov 25, 2014 at 6:11

1 Answer 1

3

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();
      });
    }
  };

});

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.