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');
  };      
};
1
  • You have missed the closed tag in the input field Commented Mar 4, 2014 at 12:56

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, can you explain why it works for an object and not for a normal variable?
By using a "dot", you are making AngularJS look up the prototype chain. Read more here: stackoverflow.com/questions/18716113

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.