Angular directive: multiple values ​​from directive to scope

I want to expose multiple values ​​from attributes from directive to $ scope. The directives are generated dynamically and look like this:

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

      

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

+3


source to share


2 answers


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>
      

Run codeHide result


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

+4


source




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>
      

Run codeHide result


+1


source







All Articles