2016-09-28 52 views
0

在審查角度的採訪question and answers,我注意到,作者寫控制器的語法如下:角控制器語法

function Customer($scope) 
{ 
     $scope.CustomerName = "Shiv"; 
     $scope.CustomerCode = "1001"; 
     $scope.Add = function() { 
     } 
     $scope.Update = function() { 
     } 
} 

我習慣於寫控制器以這樣的方式

app.controller('Customer', function($scope) { 
    $scope.CustomerName = "Shiv"; 
    $scope.CustomerCode = "1001"; 
    $scope.Add = function() {} 
    $scope.Update = function() {} 
}); 

我將如何在角度項目中使用作者控制器語法?

回答

1

約翰爸爸誰是角國家認可的「大師」,他建議建立控制器在你的第一個例子。有關使用情況,請參閱HERE

0

app.controller(「客戶」,客戶($範圍))

0

作者只是使用一個命名函數,而不是像你一樣直接傳遞一個匿名函數。

app.controller('Customer',Customer); 

function Customer($scope) { 
    ... 
} 

另外,我建議你尋找到依賴注入,這是由它的嚴格模式需要一個角的最佳實踐。是這樣的...

app.controller('Customer',Customer); 

// Dependencies declared here 
// This tells angular what to inject into your controller 
Customer.$inject = ['$scope']; 

// Controller Constructor Function 
// You can now safely use $scope. 
function Customer($scope) { 
    ... 
} 

退房​​。底部有一個用於BadController,GoodController1和GoodController2的JS示例,可以改進您的風格。作者去了GoodController2語法