如何在angularJs自定义指令中传递值作为属性

时间:2022-02-14 09:34:37

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="angular.js@1.4.x" 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

下面是柱塞链接:http://plnkr.co/edit/r95YGxS19cMvWMWZMPcN

Please help.

请帮助。

1 个解决方案

#1


3  

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

您需要定义该指令的范围,然后,temp将是该指令范围内的一个变量。

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

如果需要将MainCtrl值绑定到directive,那么可以使用=而不是@,就像在这个Plunker中一样

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

还有一个(&)指向MainCtrl中的一个函数。检查这个文档

#1


3  

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

您需要定义该指令的范围,然后,temp将是该指令范围内的一个变量。

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

如果需要将MainCtrl值绑定到directive,那么可以使用=而不是@,就像在这个Plunker中一样

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

还有一个(&)指向MainCtrl中的一个函数。检查这个文档