2014-09-01 91 views
0

我試圖練習角度,我堅持這一點。角ng鍵點擊加載控制器

我該如何製作ng-click加載displayController?還是我做錯了這個方式?

的角度

var bible = angular.module('bible', []); 

// Load the Books 
bible.controller('listController', ['$scope', '$http', function($scope, $http) { 

    $http.get('books.json').success(function(data) { 
     $scope.books = data 
    }); 

}]); 

bible.controller('displayController', function($scope) { 
    $scope.test = "TEST TEXT"; 
}); 

的HTML

<div class="row"> 
     <div class="col-md-12" ng-controller="listController"> 
      <table class="table"> 
       <thead> 
        <th>Testament</th> 
        <th>Title</th> 
        <th>Chapters</th> 
       </thead> 
       <tbody> 
        <tr ng-repeat="book in books"> 
         <td>{{book.testament}}</td> 
         <td><a href="#" ng-click="displayController">{{book.title}}</a></td> 
         <td>{{book.chapters}}</td> 
        </tr> 
       </tbody> 
      </table> 

      <div class="display-book" ng-controller="displayController"> 
       {{test}} 
      </div> 
     </div> 
    </div> 
+0

我想這不是你應該這樣做的方式。不管是什麼'ngClick',都應該放在主控制器的'$ scope'中,在你的情況下,是'listController'。你想用這個做什麼? – 2014-09-01 08:56:00

回答

3

你不需要有額外的控制器。我想你想顯示關於點擊書籍的其他信息。

使用的參考和ngIf

var bible = angular.module('bible', []); 

// Load the Books 
bible.controller('listController', ['$scope', '$http', function($scope, $http) { 
    $scope.selectedBook = null; 
    $http.get('books.json').success(function(data) { 
     $scope.books = data 
    }); 
}]); 

和HTML:

<div class="row"> 
    <div class="col-md-12" ng-controller="listController"> 
     <!-- will be shown, as long as not book is selected --> 
     <table data-ng-if="selectedBook == null" class="table"> 
      <thead> 
       <th>Testament</th> 
       <th>Title</th> 
       <th>Chapters</th> 
      </thead> 
      <tbody> 
       <tr ng-repeat="book in books"> 
        <td>{{book.testament}}</td> 
        <td><a href="#" ng-click="selectedBook = book;">{{book.title}}</a></td> 
        <td>{{book.chapters}}</td> 
       </tr> 
      </tbody> 
     </table> 
     <!-- will be shown, when a book got selected --> 
     <div data-ng-if="selectedBook != null" class="display-book"> 
      <!-- display the selection table again --> 
      <button data-ng-click="selectedBook = null">Back</button> 

      {{selectedBook.title}} 
     </div> 
    </div> 
</div> 
1

你要調用一個單獨的控制器不能你像下面一個單獨的函數實現的功能爲什麼,

bible.controller('listController', ['$scope', '$http', function($scope, $http) { 

    $http.get('books.json').success(function(data) { 
     $scope.books = data 
    }); 

    $scope.display = function(){ 
     // **YOUR CODE COMES HERE** 
    } 
}]); 

<td><a href="#" ng-click="display()">{{book.title}}</a></td>