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