AngularJS文本框返回未定义的值

时间:2014-09-24 05:58:35

标签: angularjs

当我按下我的按钮检查bootstrap模式时,我想在我的控制台中打印我的文本框的值。但我的文本框返回一个未定义的。似乎所有的代码都运行得很完美。

<!doctype html>
<html ng-app="app" ng-controller="ModalDemoCtrl">
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.js"></script>
<script src="example1.js"></script>
</head>
<body>

<div ><button class="btn btn-default" ng-click="open('lg')" >Large modal</button>
<script type="text/ng-template" id="myModalContent">
<div class="modal-header">
    <h3 class="modal-title">I'm a modal!</h3>
</div>
<input type="text" ng-model="new1" /><button ng-click="check()" >check</button>
<div class="modal-footer">
    <button class="btn btn-primary" ng-click="ok()">OK</button>
    <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
</div>
</body>
</html>

这是我的javascript

var app = angular.module('app', ['ui.bootstrap']);
//var ModalDemoCtrl = function ($scope, $modal, $log) {
app.controller('ModalDemoCtrl',['$scope', '$modal','$log','$rootScope',
function controller($scope, $modal, $log, $rootScope)
{
    $scope.open = function (size) {
        $scope.val = "";
        var modalInstance = $modal.open({
            templateUrl: 'myModalContent',
            controller: ModalInstanceCtrl,
            size: size,
            backdrop: 'static',
            resolve: {
                items: function () {
                    return $scope.items;
                }
            }
        });

        modalInstance.result.then(function (selectedItem) {
            $scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
}]);


var ModalInstanceCtrl = function ($scope,$rootScope, $modalInstance) {

$scope.check = function()
{
    console.log($scope.new1);
};

$scope.ok = function () {
    $modalInstance.close();
};

$scope.cancel = function () {
    $modalInstance.dismiss('cancel');
};
};

3 个答案:

答案 0 :(得分:2)

为了访问$ scope变量,你需要使用$ parent,因为它在模态中创建了一个子范围

HTML代码(已更改):

<input type="text" ng-model="$parent.new" /><button ng-click="check()" >check</button>

Working Fiddle

答案 1 :(得分:1)

在对象初始化而不是范围声明新属性:

var ModalInstanceCtrl = function ($scope,$rootScope, $modalInstance) {

        $scope.model= {};

        $scope.check = function()
        {
            alert($scope.model.new);
        };

        $scope.ok = function () {
            $modalInstance.close();
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    };

http://plnkr.co/edit/A6I158T9I5kGyChgIDK2?p=preview

答案 2 :(得分:0)

您可以在“检查”功能

中将ng-model作为参数传递
<input type="text" ng-model="new1" /><button ng-click="check(new1)" >check</button>

 $scope.check = function(new1)
{
  console.log("value..."+new1);
};