2016-05-15 42 views
1

下角的js代碼拋出錯誤 - 「angular.js:13550類型錯誤:無法讀取屬性 '編譯' 的未定義」 爲代碼 -angular.js:13550 TypeError:無法讀取未定義的屬性'compile'?

HelloWorld.html的

<!DOCTYPE html> 
    <html ng-app="module1"> 
    <head> 
     <title>My First Custom Directive</title> 
     <script src="../angular.js"></script> 
     <script src="helloworldDirective.js"></script> 
    </head> 
    <body> 
     <hello-world></hello-world> 
    </body> 
    </html> 

helloWorldDirective.js -

(function() { 

    var module1=angular.module('module1',[]); 
    module1.directive('helloWorld',function(){ 
     return 
     { 
      template:'Hello Somesh!!Keep it up.' 
     }; 

    }); 


}()); 

但是,當我用下面的代碼替換java腳本文件它的作品。

(function() { 

    var module1=angular.module('module1',[]); 
    var helloWorld=function() 
{ 
var directive={};  
directive.template='Hello Somesh!!Keep it up.'; 
return directive; 
} 
module1.directive('helloWorld',helloWorld); 

}()); 

這兩個代碼基本上是做同樣的事情,但一個失敗。有什麼想法嗎?

回答

1

在第一個示例中,存在「無法訪問的代碼錯誤」

您可以修復這個錯誤有:

return template = {template: 'Hello Somesh!!Keep it up.'}; 

否則你無法得到的指針屬性。

+0

對不起:首先你的第一個例子沒有工作,現在它。唯一的區別是:我把整個東西放在一行中,並在冒號和引號之間設置空格,所以它只是在上面,但沒有賦值。 –

0

JavaScript的自動分號注射變成這樣:

return 
     { 
      template:'Hello Somesh!!Keep it up.' 
     }; 

到這一點:

return; 
     { 
      template:'Hello Somesh!!Keep it up.' 
     }; 

回報,其次是一個無用的代碼塊。 (template:被視爲標籤。)

調試提示:JSHint或JSLint會爲您找到此錯誤。

樣式提示:在JavaScript中,始終在同一行上保留開放大括號...雖然只有returnthrow聲明受此特定問題影響。

+0

謝謝它幫助:) –

0

使用此方法來定義你的指令:

app.directive('helloWorld', [function() { 
    return { 
     restrict: 'E', 
     transclude: false, 
     template: 'Hello Somesh!!Keep it up.' 
    } 
}]); 
相關問題