以两种不同的方式创建简单指令

时间:2017-11-05 08:47:19

标签: javascript angularjs angularjs-directive

我试图以两种不同的方式创建一个非常简单的指令。一个使用匿名函数(传统方式)和其他使用命名函数。命名函数给出了以下错误 -

TypeError: Cannot read property 'compile' of undefined

这是我的代码:

angular.module("exampleApp", []);
// first way--working fine
angular.module("exampleApp")
  .directive("showProducts", function() {

    return function() {

      console.log('first');
    };

  });

// second way--not working fine
angular.module("exampleApp")
  .directive("showProducts", second())


function second() {
  return function() {

    console.log('second');
  };

};
<html ng-app="exampleApp">

<head>
  <title>Directives</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.js"></script>
</head>

<body>
  <div class="panel panel-default">
    <div class="panel-body">
      pls chk console-
      <show-products></show-products>
    </div>
  </div>
</body>

</html>

我无法找到原因。

2 个答案:

答案 0 :(得分:0)

您必须提供指定函数的引用,而不是调用它。

更改此内容:.directive("showProducts", second());

对此:.directive("showProducts", second);

答案 1 :(得分:0)

只需删除括号,然后将其设为:

    angular.module("exampleApp")
  .directive("showProducts", second) /* call the reference of the function here */


function second() {
  return function() {

    console.log('second');
  };

};

顺便说一下,如果你注册两个指令,angularjs会同时考虑它们。阅读更多here

相关问题