Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass parameters to several AngularJS directive instances?

Newbie question on angularJS, but don't see analogous case in tutorials having searched.

How do I pass different parameters to individual div instances using the same directive definition? Here I'd expect to see red green blue but instead I see blue blue blue in the HTML. I see the controller is getting called before the link.

http://jsfiddle.net/gradualstudent/Y2bBy/

<!DOCTYPE html>
<html >
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
    <script>
      var app = angular.module('myApp', []);

      app.directive("element", function () {
        return {
          restrict: "A",
          template: '<h1>{{type}}</h1>',
          link: function (scope, element, attrs) {
            scope.type = attrs.element;
            console.log("Setting:  "+scope.type);
          },
          controller: function ($scope) {
            console.log("Checking: "+$scope.type);
          }
        };
      })

    </script>
</head>
<body ng-app="myApp">
  <div element="red">1</div>
  <div element="green">2</div>
  <div element="blue">3</div>

</body>
</html>
like image 914
prototype Avatar asked Dec 05 '25 20:12

prototype


2 Answers

all instances of your directive use the same scope and every time the link function is called, it overrides the previously set scope.type. if you create an isolated scope then it will work because each instance of the directive will get its own scope:

    app.directive("element", function () {
    return {
      restrict: "A",
      scope: {},
      template: '<h1>{{type}}</h1>',
      link: function (scope, element, attrs) {
        scope.type = attrs.element;
        console.log("Setting:  "+scope.type);
      },
      controller: function ($scope) {
        console.log("Checking: "+$scope.type);
      }
    };
  })
like image 140
akonsu Avatar answered Dec 08 '25 10:12

akonsu


In the example you have shared, the directives share the parent scope. Since all directive share the same parent scope there is only one variable type available.

The options that you have is to do either

scope:true   //Creates new scope for each directive instance

or

scope:{} //as provided by akonsu. Creates an isolated scope.

Just for completeness please spend time on understanding scope prototypal inheritance https://github.com/angular/angular.js/wiki/Understanding-Scopes

like image 33
Chandermani Avatar answered Dec 08 '25 09:12

Chandermani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!