2015-04-05 52 views
5

我花了一些時間來玩AngularJS Bootstrap彈出窗口,意圖很好,但我想要做的就是綁定它,並且它是依賴腳本到同一個控制器,我不能現在開始工作就是關閉按鈕。如果我創建一個新的控制器,並注入$ modalInstance它工作得很好,我可以wireup關閉按鈕沒有任何問題,但我不想第二個控制器,它似乎是複雜化:我想我的所有控制器邏輯在formController中真的。

爲什麼我實際上需要兩個控制器?在兩個控制器之間傳遞範圍對我來說似乎有些過分,而且越大的項目變得越不可管理。我是否試圖過度簡化這不必要的? :)

腳本:

(function(){ 
    var app = angular.module('ngModalDemo', ['ui.bootstrap']) 
    .controller('formController', function($scope, $modal){ 
     $scope.openModal = function() {       
      var modalInstance = $modal.open({ 
       templateUrl: 'SomeModal.html', 
       controller: 'formController'            
      }); 
     }; 
     $scope.closeModal = function() { 
      // Code needed here :) 
     }; 
    }) 
})(); 

的HTML體(原諒了DEMO的目的腳本的HTML):

<div ng-controller="formController"> 
     <button class="btn btn-default" ng-click="openModal()">Let's do some stuff!</button> 

     <script type="text/ng-template" id="SomeModal.html"> 
      <div class="modal-header">Do some stuff in this modal y'all.</div> 
      <div class="modal-footer"> 
       <button class="btn btn-info" ng-click="closeModal()">Close</button> 
      </div> 
     </script> 
    </div> 

基於卡斯帕爾斯輸入:)

答案
(function(){ 
      var app = angular.module('ngModalDemo', ['ui.bootstrap']) 
      .controller('formController', function($scope, $modal, $log){ 
       $scope.openModal = function() {       
        var modalInstance = $modal.open({ 
         templateUrl: 'SomeModal.html', 
         controller: [ 
          '$scope', '$modalInstance', function($scope, $modalInstance){ 
           $scope.closeModal = function() { 
            $modalInstance.close(); 
           }; 
          } 
         ]       
        }); 
       }; 
      }) 
     })(); 
+0

一個獨立的模態控制器的偉大工程,如果模式將是由許多控制器 – gaurav5430 2015-12-02 18:02:54

回答

7

我一直在努力解決同樣的問題,我想出的最好的東西就是使用匿名函數作爲模態控制奧勒。這樣所有的邏輯都在同一個控制器中,並且你不必爲每個模態窗口創建單獨的控制器。

這應該是這樣的:

(function(){ 
    var app = angular.module('ngModalDemo', ['ui.bootstrap']) 
    .controller('formController', function($scope, $modal){ 
     $scope.openModal = function() {       
      var modalInstance = $modal.open({ 
       templateUrl: 'SomeModal.html', 
       controller: [ 
        '$scope', '$modalInstance', 'data', function($scope, $modalInstance, data) { 
         $scope.data = data; 
         $scope.ok = function() { 
          $modalInstance.close(); 
         }; 
         $scope.closeModal = function() { 
          $modalInstance.dismiss(); 
         }; 
        } 
       ] 
      }); 
     }; 
    }) 
})(); 

PS。沒有測試過上面的代碼,只是把它們放在你提供的代碼和我的一個項目中的片段中。

+0

謝謝卡斯帕爾斯共享,即工作一種享受,我已經添加了實際的代碼我簡化了參考原始問題:) – NewZeroRiot 2015-04-05 20:31:41

0

你也可以試試這個

var modalInstance = $modal.open({ 
           templateUrl : 'someTemplate.html', 
           scope : $scope, 
           size : 'md' 
          }); 
相關問題