2

As in the title. I would like to increment value inside directive template.

I tried this:

var ngApp = angular.module("ngApp", []);

ngApp.controller("AppCtrl", function(){
  var app = this;
  app.counter = 1;
  app.foo = function(){
    app.counter++;
    return app.counter;
  }
});

ngApp.directive("box", function(){
  return {
    restrict: "E",
    template: "<div>BOX - {{app.foo()}}<div>"
  }
});

But it does not work. Any ideas?

2
  • If you are going to use your directive in a repeat then you could just use $index. Check out ngRepeat. Commented Aug 7, 2014 at 8:18
  • I know it, but I need increment the value when the directive is compiled the first time as Wawy said. Commented Aug 7, 2014 at 8:20

3 Answers 3

2

What would you like to do? Increment the value when the directive is compiled the first time? If so then you can do this:

ngApp.directive("box", function(){
  function ctrl($scope) {
    $scope.counter = $scope.app.foo();
  }
  return {
    restrict: "E",
    scope: true,
    controller: ctrl
    template: "<div>BOX - {{counter}}<div>"
  }
});
Sign up to request clarification or add additional context in comments.

Comments

1

Try like this , you dont need to return any value , but you should call foo function, for example on click or somwhere else in your code where you need it

var ngApp = angular.module("ngApp", []);
ngApp.controller("AppCtrl", function(){
  var app = this;
  app.counter = 1;
  app.foo = function(){
    app.counter++;  
  }
});

ngApp.directive("box", function(){
  return {
    restrict: "E",
    template: "<div ng-click='app.foo()'>BOX - {{app.counter}}<div>"
  }
});

1 Comment

then please explain what you need, because in your example it will work once and you counter will be 2
0

You can put your controller inside of your directive:

var ngApp = angular.module("ngApp", []);

ngApp.directive("box", function(){
  return {
    restrict: "E",
    controllerAs: 'app',
    controller: function(){
       var app = this;
       app.counter = 1;
       app.foo = function(){
          app.counter++;
       }
    },
    template: "<div>BOX - {{app.foo()}}<div>"
  }
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.