nataila nataila - 2 months ago 6
AngularJS Question

angularJS how to change attrs in directive's link

I set a progress in my app

I want to controll The progress in angular's directive

but how can I change

data-value
and
data-total
in directive's link func?

app.html

<div class="ui indicating small progress" data-value="39" data-total="50" plan-progress>
<div class="bar">
<div class="progress"></div>
</div>
</div>


In this html, I want change
data-value
and
data-total


I try this:

app.js

todoApp.directive('planProgress', function() {
return {
link: function(scope, elem, attrs) {
attrs.value = 10
attrs.total = 20
elem.progress();
}
};
});


But it doesn't work

so I want to know how to change it in my directive?

Answer

Use attrs.$set() in your link function and recompile the element. Also, don't forget to inject the $compile service to your directive. In your html you've added the directive as an attribute but didn't mention it in the restrict value in your directive definition. You need to mention it in directive definition. See the code bellow:

todoApp.directive('planProgress', function($compile) {
    return {
      restrict: 'A',
      link: function(scope, elem, attrs) {
        attrs.$set('value', 10);
        attrs.$set('total', 20);
        $compile(elem)(scope);
      }
    };
  });