2014-08-31 2 views
6

응용 프로그램의 여러 위치에서 인스턴스화 할 수있는 모달을 만들려고합니다. 여기서 주어진 예제에서 : Angular directives for Bootstrap 모달 컨트롤러는 모달을 인스턴스화하는 컨트롤러와 동일한 파일에 있습니다. 모달 컨트롤러를 "app"컨트롤러와 분리하고 싶습니다.별도의 js 파일에있는 컨트롤러가있는 각도 ui 모달

index.html을 :

<!DOCTYPE html> 
<html ng-app="modalTest"> 

    <head> 
    <link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> 
    </head> 

    <body ng-controller="modalTestCtrl"> 
    <button ng-click="openModal()">Modal</button> 

    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script> 
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.10.0/ui-bootstrap.min.js"></script> 
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.10.0/ui-bootstrap-tpls.min.js"></script> 
    <script type="text/javascript" src="modalTest.js"></script> 
    </body> 

</html> 

컨트롤러 :

var app = angular.module('modalTest', ['ui.bootstrap']); 

app.controller('modalTestCtrl', ['$scope', '$modal', function($scope, $modal) { 
    $scope.openModal = function() { 
     var modalInstance = $modal.open({ 
      templateUrl: 'modal.html', 
      controller: 'modalCtrl', 
      size: 'sm' 

     }); 
    } 
}]); 
// I want this in another JavaScript file... 
app.controller('modalCtrl', ['$scope', function($scope) { 
    $scope.hello = 'Works'; 
}]); 

modal.html :

<div ng-controller="modalCtrl"> 
    <div class="modal-header"> 
     <h3 class="modal-title">I'm a modal!</h3> 
    </div> 
    <div class="modal-body"> 
     <h1>{{hello}}</h1> 
    </div> 
    <div class="modal-footer"> 
     <button class="btn btn-primary" ng-click="ok()">OK</button> 
     <button class="btn btn-warning" ng-click="cancel()">Cancel</button> 
    </div> 
</div> 

다른 자바 스크립트 파일과 어떻게 든 modalCtrl을 넣어 어떤 방법이 있나요 컨트롤러 (modalCtrl)를 modalTestCtrl?

rob

+0

컨트롤러를 사용해야하는 특별한 이유가없는 한 지시문을 사용하고 싶을 것입니다. – tommybananas

+0

모달은 로그인 모달이며 세션 시간이 초과되면 모달이 표시되어야한다고합니다. . 그런 다음 모달 컨트롤러에 모든 로그인 논리가 있어야합니다. – user3594184

답변

9

물론 가능합니다. 우선 함수 선언을 사용해야합니다. 당신이 코드가 작동하는 위의 변경

app.controller('modalTestCtrl', ['$scope', '$modal', function($scope, $modal) { 
$scope.openModal = function() { 
    var modalInstance = $modal.open({ 
     templateUrl: 'modal.html', 
     controller: modalCtrl, //This must be a referance, not a string 
     size: 'sm' 

    }); 
} 
}]); 

:

// modalCtrl.js 
// This file has to load before modalTestCtrl controller 
function modalCtrl ($scope) { 
    $scope.hello = 'Works'; 
}; 

그런 다음, 같은 modalTestCtrl을 변경합니다.

+0

고맙습니다. – user3594184

+0

기꺼이 도와 드리겠습니다. – turhanco

+0

미니 경고 : modalCtrl 함수는 자체 실행 함수가 아닌 modalCtrl.js에서 직접 선언해야합니다. D (다음과 같은 사실을 알게 될 때까지 15 분 동안 괴롭혔습니다. D) –

관련 문제