Search code examples
javascriptangularjsangular-ui

ng-model input inside an angular-ui modal controller is undefined


In my modal template I'm trying to use ng-model to assign a value to the scope of my controller ($scope.name), but it doesn't work. It gives me undefined. What am I doing wrong? Plunker here

I expect that the modal creates its own scope, and puts name into that scope because I used ng-model. It seems to be active inside the modal controller as I can output it fine using {{name}}

<div ng-controller="ModalDemoCtrl">
    <script type="text/ng-template" id="myModalContent.html">
        <div class="modal-body">
            Name: <input type="text" ng-model="name">
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" ng-click="ok()">OK</button>
        </div>
    </script>
    <button class="btn" ng-click="open()">Open me!</button>
</div>

Javascript:

angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function ($scope, $modal, $log) {    
  $scope.open = function () {
    var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      controller: ModalInstanceCtrl
    });
  };      
};

var ModalInstanceCtrl = function ($scope, $modalInstance) {    
  $scope.ok = function () {
    $modalInstance.close($scope.name);
    alert('name was: ' + $scope.name)
  };    
  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };      
};

Solution

  • The model name is created inside a different scope. Use an object:

    var ModalInstanceCtrl = function ($scope, $modalInstance) {
        $scope.data = {
            name:""
        };
        $scope.ok = function () {
            alert('name was: ' + $scope.data.name);
            $modalInstance.close($scope.data.name);
        };
    

    Plunk