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

时间:2017-09-13 07:39:00

标签: 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>

我怀疑为什么每次使用custom-heading指令时都只操作返回对象?通常每次使用customHeading指令时都应将index赋值为1,但事实并非如此。我试过并发现只有在使用指令时才会执行return内部的函数。它是与指令实例相关的东西,它只创建一次。有人可以解释在后台发生的事情吗?

如果我们两次使用相同的控制器,无论是在差异视图中还是在同一页面中嵌套它们,并将索引指定为1然后递增并记录其值,我们会看到每次使用该控制器时都会重新分配索引值。 #39; s因为每次都执行控制器功能。

在指令的情况下,只有返回对象内的函数(控制器,链接等)一次又一次地执行,无论我们使用该指令多少次。而不是在回归之前写的是什么,这就是我想知道的。为什么只执行返回函数。我怀疑的不是范围。理想情况下,只要我们使用,就应该执行指令的整个回调函数。但只执行返回部分。

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 =&gt;

<custom-heading></custom-heading>
<custom-heading></custom-heading>
<custom-heading></custom-heading>

在控制台中,我们将其视为o / p =&gt;

In directive
In controller
In controller
In controller

现在,如果有人能解释为什么&#34;在指令&#34;仅记录一次。控制器的行为符合预期。

1 个答案:

答案 0 :(得分:1)

  

现在,如果有人能解释为什么&#34;在指令&#34;仅记录一次。控制器的行为符合预期。

您只注册了一次名为customHeading的新指令模块,因此您看到了 In directive 1次

  

我试过并发现每次使用指令时都只执行return内的函数。

因为你打了3次电话:

<custom-heading></custom-heading>
<custom-heading></custom-heading>
<custom-heading></custom-heading> 

指令控制器被调用3次