pkberlin
pkberlin

Reputation: 852

Angular directive: multiple values from directive to scope

I want to expose multiple values from attributes from an directive to the $scope. The directives are generated dynamically and looks like this example:

<my-directive first-value="foo" second-value="bar" third-value="foobar"></my-directive>

I need the values in the $scope for give them to the template and work with them.

Upvotes: 3

Views: 3411

Answers (2)

MarcoS
MarcoS

Reputation: 17711

Easy... :-)

var app = angular.module('app', []);
app.controller('myCtrl', function ($scope) {});
app.directive('myDirective', function() {
  return {
    restrict: 'E',
    template: '<p>myDirective:</p>{{firstValue}}, {{secondValue}}, {{thirdValue}}',
    scope: {
      firstValue: '@',
      secondValue: '@',
      thirdValue: '@'
    },
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="myCtrl">
    <my-directive first-value="foo" second-value="bar" third-value="foobar"></my-directive>
  </div>
</div>

But you really should try to write this kind of code yourself, next time... :-)

Upvotes: 5

sylwester
sylwester

Reputation: 16498

var app = angular.module('app', []);

app.controller('homeCtrl', function ($scope) {


   

});
app.directive('myDirective', function() {

  return {
    restrict: 'AE',
    template: '<h3>My Directive</h3><p>{{firstValue}}|{{secondValue}}|{{thirdValue}}</p>',
    scope: {
      firstValue: '@',
      secondValue: '@',
      thirdValue: '@'
    },

    link: function(scope, element, attr) {

      console.log(scope.firstValue)
      console.log(scope.secondValue)
      console.log(scope.thirdValue)

    }

  }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="homeCtrl">

    <my-directive first-value="foo" second-value="bar" third-value="foobar"></my-directive>
  </div>
</div>

Upvotes: 1

Related Questions