如何初始化表单字段值?

时间:2015-05-12 14:40:19

标签: angularjs forms

有没有办法初始化以下表单字段,因此Angular代码不会显示" NaN"什么时候加载表单?将值从零开始会很好。

<input type="text" id="field1" value="0"/>
<input type="text" id="field2" value="0"/>
<br />

Total {{field1*50--field2}}

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

2 个答案:

答案 0 :(得分:4)

您可以使用ng-init指令。这是从你的plunker复制的东西。但是你应谨慎使用,这里摘录自documentation

The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope

<!DOCTYPE html>
<html ng-app>

  <head>
    <script data-require="angular.js@*" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    testing
    <input type="text" id="field1" ng-model="field1" ng-init="field1 = 0"/>
    <input type="text" id="field2" ng-model="field2" ng-init="field2 = 0"/>
    <br />

    Total {{field1*50--field2}}
    
  </body>

</html>

所以,你应该这样做:

angular.module('app', [])
  .controller('testCtrl', ['$scope',
    function($scope) {

      function init() {
        $scope.field1 = 0;
        $scope.field2 = 0;
      }
      init();
    }
  ]);
<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.css" rel="stylesheet" />
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>

<body ng-app="app">
  <div ng-controller="testCtrl">
    testing
    <input type="text" id="field1" ng-model="field1" />
    <input type="text" id="field2" ng-model="field2" />
    <br />Total {{ field1 * 50 - -field2}}
  </div>
</body>

</html>

答案 1 :(得分:0)

您只需在HTML中添加controller并为ng-model字段分配<input>,并使用控制器中的某些值对其进行初始化,而不是在value中使用<input> {1}}。

这足以为字段

设置默认值

以下是您的代码的工作插件,

http://embed.plnkr.co/Ssk1bP6LWq9YgAIDYaEk/preview

希望这有助于!!!!