0

I have a directive which compiles a template and uses a variable on scope to increment index values in the template.

Here is my directive:

angular.module('app').directive( 'ingredient', function ( $compile, persistedCount, $templateRequest) {


return {
    restrict: 'E',
    template: '<div sticky-nav><button type="button" class="btn btn-success" ng-click="add()">add ingredient  <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> </button></div>',
    controller: function ( $scope, $element ) {
      $scope.ingredientNumber = persistedCount.ingredients = persistedCount.ingredients || 0;


  $scope.add = function () {

    $templateRequest("templates/ingredients-template.html").then(function(html){
        compileIngredients(html);   
    });

    function compileIngredients(html){
          $element.parent().append($compile(html)($scope));
          console.log($scope.ingredientNumber);
    }

    persistedCount.ingredients++;
    console.log(persistedCount.ingredients);


};

persistedCount Service:

angular.module('app').service('persistedCount',function(){
return{
    persistedCount:{
        ingredients: 0,
        directions:0,
        notes:0
      }
    }
});

I'm using one variable in my template $scope.ingredientNumber, really just to increment the index values like this.

<formly-form model="vm.model.data.ingredients[ingredientNumber].quantity" fields="vm.fields.data.ingredients[ingredientNumber].quantity"> </formly-form>

The problem is that the $scope.ingredientNumber never increases, but the persistedCount does. I think this is a closure issue? It seems like $scope.incrementNumber never picks up a new value after being set initially?

When I set $scope.ingredientNumber = persistedCount.ingredients = persistedCount.ingredients || 0; inside of the $scope.add function it incriments correctly but everything on the DOM picks up that value as well. So instead of having 0,1,2,3 I have 3,3,3,3

1 Answer 1

1

This line is run only once according to your code the first time the controller is loaded:

$scope.ingredientNumber = persistedCount.ingredients = persistedCount.ingredients || 0;

So it seems there's a problem with your logic.

Side note: it is considered bad practice to manipulate the DOM via a controller. Are you sure you can't simplify your solution by creating a directive for an ingredient with the template you are loading and just use ng-repeat to display the list of ingredients?

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.