9

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');
  };      
};
Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43
Nick
  • 11,483
  • 8
  • 41
  • 44

1 Answers1

22

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

AlwaysALearner
  • 43,759
  • 9
  • 96
  • 78
  • 1
    Thanks, can you explain why it works for an object and not for a normal variable? – Nick Mar 04 '14 at 13:00
  • 4
    By using a "dot", you are making AngularJS look up the prototype chain. Read more here: http://stackoverflow.com/questions/18716113 – AlwaysALearner Mar 04 '14 at 13:01