javascript angular-ui 模态控制器内的 ng-model 输入未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22172462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:36:42  来源:igfitidea点击:

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

javascriptangularjsangular-ui

提问by Nick

In my modal template I'm trying to use ng-modelto 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

在我的模态模板中,我试图用来ng-model为我的控制器 ( $scope.name)的范围分配一个值,但它不起作用。它给了我undefined。我究竟做错了什么?普伦克在这里

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

我希望模态创建自己的范围,并放入name该范围,因为我使用了ng-model. 它似乎在模态控制器内处于活动状态,因为我可以使用{{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:

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');
  };      
};

回答by AlwaysALearner

The model nameis created inside a different scope. Use an object:

该模型name是在不同的范围内创建的。使用对象:

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

Plunk

Plunk