2017-11-05 1 views
0

두 가지 다른 방법으로 아주 간단한 지시문을 만들려고합니다. 하나는 익명 함수 (전통적인 방법)를 사용하고 다른 하나는 명명 된 함수를 사용합니다.두 가지 다른 방식으로 간단한 지시문을 만듭니다.

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>

가 나는 이유를 찾을 수 없습니다입니다 : 명명 된 기능은 다음 error--

TypeError: Cannot read property 'compile' of undefined 

다음 날주고있다 내 코드입니다.

+0

같은 이름의 지시문을 두 번 작성했습니다. 어떤 각도로 고려할 것인가? 둘 다 고려 된 것을 볼 수 있습니다. 또한 왜 두 번째가 먼저 실행됩니까? –

답변

0

간단하게 다음과 같이 그것을 괄호를 제거합니다 : 여기에 .directive("showProducts", second());

변경 당신이 지시를 등록하면 그건 그렇고

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


function second() { 
    return function() { 

    console.log('second'); 
    }; 

}; 

는 AngularJS와 고려한다 그들 둘 다. 더 읽기 : here.

+0

우수! 잘 작동합니다. 하지만 같은 이름의 지시어를 두 번 만들었습니다. 어떤 각도로 고려할 것인가? 둘 다 고려 된 것을 볼 수 있습니다. 또한 왜 두 번째가 먼저 실행됩니까? –

+0

@DebnathChakraborty 예 모두 고려됩니다.) 자세한 내용은이 링크를 확인하십시오. https://stackoverflow.com/questions/31702149/if-i-register-two-different-directives-with-the-same-name- in-two-modules-will-t –

+0

@DebnathChakraborty이 말을 해답을 업데이트했습니다;) –

0

명명 된 함수에 대한 참조를 제공해야합니다. 호출하지 말아야합니다. .directive("showProducts", second);

+0

맞습니다! –

관련 문제