Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
  };      
};
like image 533
Nick Avatar asked Mar 04 '14 12:03

Nick


People also ask

What is nG model in AngularJS?

AngularJS ng-model Directive. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

How to bind an input field to a variable in AngularJS?

The ng-model Directive. With the ng-model directive you can bind the value of an input field to a variable created in AngularJS. Example. <div ng-app="myApp" ng-controller="myCtrl">. Name: <input ng-model="name">. </div>.

Why is ngmodel not re-rendering my input?

If only properties of the object or collection change, ngModel will not be notified and so the input will not be re-rendered. The model must be assigned an entirely new object or collection before a re-rendering will occur.

How to open a modal from another component in angular?

Create a new component with Angular CLI and add some HTML code to the template. 2. Inject MdbModalService to the component from which you want to open the modal and use the open method. You can inject data to the modal by passing it to the data parameter in the modal options.


1 Answers

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

like image 66
AlwaysALearner Avatar answered Sep 30 '22 19:09

AlwaysALearner