2013-05-16 38 views
1

我正在開發演示應用程序來學習AngularJS。幾件讓我困擾的事情。很少有基本的問題困擾着我與AngularJS相關

1 -是什麼苦惱,因爲無論是工作的罰款

<div ng-controller="Page2Ctrl"> 

</div> 

when('/page2', {templateUrl: 'views/flow1/page2.html', controller: 'Page2Ctrl'}). 

之間的差異。即使在路由中定義了控制器,是否需要在Html中定義ng-controller

2 -是什麼第二

function Page4Ctrl($scope){ 
    $scope.pageName = "Page 4 loaded." 
} 

而且

app.controller('Page4Ctrl', function ($scope) { 
    $scope.pageName = "Page 4 loaded." 
}); 

之間的差別很冗長,需要額外的輸入。任何有關使用它們的建議?

3 -假設我正在爲客戶開發一個CRUD應用程序。我製作了一個CustomerController.js文件,我想把所有與客戶相關的方法(創建,讀取,更新,刪除,FindById,FindAll等)。如下所示。這是正確的方法還是控制器應該是一個包含所有CRUD方法的CustomerController?

app.controller('CustomerCreateController', function ($scope) {}); 
app.controller('CustomerEditController', function ($scope) {}); 
app.controller('CustomerDeleteController', function ($scope) {}); 

回答

4

1)當直接鍵入ng-controller到您的觀點,即查看有直接領帶該控制器。在路線中定義控制器允許您重新使用該視圖以滿足其他需求。

例如,您有一個顯示名稱列表的視圖。

<ul ng-controller="ListCtrl"> 
    <li ng-repeat="item in items">{{item.name}}</li> 
</ul> 

現在某個地方在您的應用程序否則你有一個顯示你需要再次做同樣的事情的名單完全相同的結構。

<ul ng-controller="MyOtherListCtrl"> 
    <li ng-repeat="item in items">{{item.name}}</li> 
</ul> 

如果刪除ng-controller屬性,你可以重用此<ul/>

<ul> 
    <li ng-repeat="item in items">{{item.name}}</li> 
</ul> 

.when('/list1', {templateUrl: 'list.html', controller: 'ListCtrl'}) 
.when('/list2', {templateUrl: 'list.html', controller: 'MyOtherListCtrl'}) 

2)app.controller作用域控制器的模塊,而其他創建控制器在全球範圍內。

3)我依賴於你如何組織你的應用程序,但只需創建一個具有$scope編輯,刪除和創建方法的CustomerController。該控制器可以採取服務的依賴或$resoruce

app.controller('CustomerController', function ($scope, customerService) { 
    $scope.add = function(customer){ 
     //add customer with customerService 
    }; 
    $scope.edit = function(customer){ 
     //edit customer with customerService 
    } 
    $scope.delete = function(customer){ 
     //delete customer with customerService 
    } 
}); 

如果你想單獨的頁面,你仍然可以重複使用相同的控制器。

.when('/add', {templateUrl: 'add.html', controller: 'CustomerController'}) 
.when('/edit', {templateUrl: 'edit.html', controller: 'CustomerController'}) 
.when('/delete', {templateUrl: 'delete.html', controller: 'CustomerController'}) 
+0

謝謝並理解每一個字。只要我進步,我會在上面提到的3個代碼中發佈更多的問題。 – Pirzada