在这个例子中
myApp.directive("customHeading",function(){
var index = 1;
return{
restrict : "E", // restrict element
templateUrl : "./views/custom-card.html",
//scope : {},
controller : function($scope){
console.log(`In controller ${index}`);
$scope.cardNumber = 'This is card '+index++;
//index++;
}// end controller
};
html =>
<custom-heading></custom-heading>
<custom-heading></custom-heading>
<custom-heading></custom-heading>
我的疑问是为什么每次我们使用自定义标题指令时只操作返回对象?通常每次我们使用 customHeading 指令时,index 都应该被分配为 1,但事实并非如此。我试了一下,发现每次使用该指令时,只执行 return 内的函数。它是否与只创建一次的指令实例有关。有人可以解释一下后台发生了什么吗?
如果我们两次使用相同的 Controller ,无论是在差异 View 中还是在同一页面中还是嵌套它们,并将索引分配为 1 然后递增并记录其值,我们会看到每次使用该 Controller 时都会重新分配索引值,这就是因为每次都会执行 Controller 函数。
在指令的情况下,无论我们使用该指令多少次,返回对象中的函数( Controller 、链接等)都会一次又一次地执行。而不是那次回归之前写的,那是我想知道的。为什么只执行 return 中的函数。我的怀疑根本不是关于范围。理想情况下,指令的整个回调函数应该在我们使用时执行。但只执行返回部分。
myApp.directive("customHeading",function(){
var index = 1;
console.log(" In directive"); // It's logged only once
return{
restrict : "E", // restrict element
templateUrl : "./views/custom-card.html",
//scope : {},
controller : function($scope){
console.log(`In controller`); // Logged 3 times
$scope.cardNumber = 'This is card '+index++;
//index++;
}// end controller
};
HTML =>
<custom-heading></custom-heading>
<custom-heading></custom-heading>
<custom-heading></custom-heading>
在控制台中,我们将其作为 o/p =>
In directive
In controller
In controller
In controller
现在,如果有人能解释为什么“In directive”只记录一次。 Controller 的行为符合预期。
最佳答案
Now, if anyone could explain why "In directive " is logged only once. Controller is behaving as expected.
你只注册了一次名为customHeading
的新指令模块,因此你看到了
在指令中
1 次
I tried and found that only functions inside return are executed every time the directive is used.
因为你调用了 3 次:
<custom-heading></custom-heading>
<custom-heading></custom-heading>
<custom-heading></custom-heading>
指令 Controller 被调用了3次
关于javascript - 在 angularjs 指令中,每次调用指令时都会执行返回的对象,但不会执行本地定义的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46191618/