javascript - 在 angularjs 指令中,每次调用指令时都会执行返回的对象,但不会执行本地定义的变量?

标签 javascript html angularjs web

在这个例子中

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/

相关文章:

javascript - 这个表达式是否总是从左到右计算?

javascript - 如何清除或替换缓存的图像

javascript - 我如何处理条纹错误 PHP

jquery - 监控类型=数量?

html - 左侧带有 Logo 的导航栏

angularjs - 如何创建具有多个选项的动态单选按钮

javascript - 为模板中的变量赋值 - Angular7

javascript - 使用 jQuery 或 JavaScript 将 <span> 与 <a> 包裹起来

AngularJS 的 javascript 执行顺序

javascript - Controller 内的作用域函数未根据 View 中的 ng-models 更新值