Firoz Ansari
Firoz Ansari

Reputation: 55

How to pass value as attribute in angularJs custom directive

I am trying to pass some value as attribute in custom directive and access inside template, but value is coming as blank.

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

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  // $scope.temp = "temp123";

});

app.directive("dirName" , function(){


  return {
    template: "<div> temp = {{temp}} </div>",
    temp:'@',

  };



});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js" data-semver="1.4.6"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <dir-name temp="my value"></dir-name>
  </body>

</html>

Here is the plunker link : http://plnkr.co/edit/r95YGxS19cMvWMWZMPcN

Please help.

Upvotes: 2

Views: 2557

Answers (1)

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

you need to define the scope of the directive then, temp will be a variable within the directive scope.

return {
    template: "<div> temp = {{temp}} </div>",
    scope: {
      temp:'@'
    }   
};

updated Plunker

if you need to bind the MainCtrl value to directive then use = instead of @ as in this Plunker

and there is another one (&) to point to a function within MainCtrl. check this DOC

Upvotes: 3

Related Questions