以两种不同的方式创建简单指令
creating simple directive in 2 different ways
我正在尝试以两种不同的方式创建一个非常简单的指令。一种使用匿名函数(传统方式),另一种使用命名函数。命名函数给我以下错误--
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>
我找不到原因。
您必须提供命名函数的引用,而不是调用它。
改变这个:.directive("showProducts", second());
为此:.directive("showProducts", second);
只需删除 括号 并使其像这样:
angular.module("exampleApp")
.directive("showProducts", second) /* call the reference of the function here */
function second() {
return function() {
console.log('second');
};
};
顺便说一下,如果您注册了两个指令,angularjs 会同时考虑它们。阅读更多 .
我正在尝试以两种不同的方式创建一个非常简单的指令。一种使用匿名函数(传统方式),另一种使用命名函数。命名函数给我以下错误--
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>
我找不到原因。
您必须提供命名函数的引用,而不是调用它。
改变这个:.directive("showProducts", second());
为此:.directive("showProducts", second);
只需删除 括号 并使其像这样:
angular.module("exampleApp")
.directive("showProducts", second) /* call the reference of the function here */
function second() {
return function() {
console.log('second');
};
};
顺便说一下,如果您注册了两个指令,angularjs 会同时考虑它们。阅读更多