Angular没有获得改变的输入值

时间:2014-08-14 07:51:29

标签: javascript angularjs

Javascript noob here :)。

我有一个基本的Angular网页,当点击“添加”(提交)按钮时,它会将输入添加到列表中。但是,如果我通过按ENTER键提交,则Angular不会识别输入字段是脏的,并且无法更新模型($ scope.newFundName) - 因此将旧值(最初为“”)添加到名单。如果我将焦点移离场并再次返回(比如说TAB,然后是BACKTAB),那么Angular会获得正确的值。如何在不手动移动焦点的情况下强制它使用输入字段的当前值?

我的代码:

<!doctype html>
<html ng-app>   <!-- test004.html -->
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <script src="../angular-1.0.0rc3.min.js"></script>
        <script type="text/javascript">
            function testController004($scope) {
                $scope.funds =  [{code:1    ,name:'Alpha'}
                                ,{code:2    ,name:'Bravo'}
                                ,{code:3    ,name:'Charlie'}];
                $scope.getFundCount = function () { return $scope.funds.length; }
                $scope.addFund = function () {
                    // if triggered by ENTER, and focus hasn't left a dirty input field, new value won't be picked up
                    $scope.funds.push({code:$scope.newFundCode,name:$scope.newFundName});
                    }
                }
        </script>
    </head>

    <body>
        <div ng-controller="testController004" class="container">
            <label># Funds: {{getFundCount()}}</label>
            <ul>
                <li ng-repeat="F in funds">
                    <span>{{F.code}}={{F.name}}</span>
                </li>
            </ul>
            <form role="form" class="form-inline">
                <label for="eFundCode">Code</label> 
                <input id="eFundCode" type="text" class="form-control" ng-model="newFundCode" />
                <label for="eFundName">Name</label> 
                <input id="eFundName" type="text" class="form-control" ng-model="newFundName" />
                <button id="eAdd" class="btn btn-info" ng-click="addFund()">Add</button>
            </form>
        </div>
    </body>
</html>

0 个答案:

没有答案