alebarros alebarros - 1 month ago 10
AngularJS Question

AngularJS - in directive counter resumes in else

I have a directive which adds text field as the past attributes. I happen to generate the id of these fields with counter ++. When the option is the same inside the if the counter is just right, but when going to the else he starts counting

JS

function test($compile) {
return {
restrict: 'E',
scope: {titulo: '@',icone:'@',corfundo:'@',tipo:'@' },
template: "<button type='button' class='btn btn-{{corfundo}} m-r-sm' ng-click='add()'><i class='fa {{icone}}'></i></button><span class='campos-texto'>{{titulo}}</span>",
controller: function ($scope, $element) {
var counter=0;
$scope.add = function () {
counter++;
var el = ''

if ($scope.tipo=='txtcurto'){
el=$compile( "<div codigo='"+counter+"' class='textbox-curto col-md-6' ></div>" )($scope);
}
else if ($scope.tipo=='txtlongo'){
el=$compile( "<div codigo='"+counter+"' class='textbox-curto col-md-12' ></div>" )($scope);
}

angular.element('#xmain').append(el)
};
}
};
}


HTML

<test titulo="Texto Curto" icone="fa-font" corfundo="danger" tipo="txtcurto"></test>
<test titulo="Texto Longo" icone="fa-font" corfundo="danger" tipo="txtlongo"></test>


RESULT
enter image description here

Answer

I'm a little unsure of what your goal is. As far as I can tell, the directive is behaving consistently as it has been written. If you are trying to guarantee the counter be unique globally, then you need to move counter out of your directive. Since counter is declared within the controller, it is initialized for each new instance of your directive.

Try the following:

var counter=0; // counter moved to here
function test($compile) {
  return {
    restrict: 'E',
    scope: {titulo: '@',icone:'@',corfundo:'@',tipo:'@'  },
    template: "<button type='button' class='btn btn-{{corfundo}} m-r-sm' ng-click='add()'><i class='fa {{icone}}'></i></button><span class='campos-texto'>{{titulo}}</span>",
    controller: function ($scope, $element) {
      // removed counter from here
      $scope.add = function () {
        counter++;
        var el = ''

        if ($scope.tipo=='txtcurto'){
          el=$compile( "<div codigo='"+counter+"' class='textbox-curto col-md-6' ></div>" )($scope);
        }
        else if ($scope.tipo=='txtlongo'){
            el=$compile( "<div codigo='"+counter+"' class='textbox-curto col-md-12' ></div>" )($scope);
        }

        angular.element('#xmain').append(el)        
      };
    }
  };
}
Comments