表格输入ng值似乎已填满,但为空

时间:2017-03-07 19:37:48

标签: javascript angularjs forms angularjs-ng-value

我正在构建一个AngularJS应用程序。我的表格有一个填充了ng值的问题。

填写输入字段,用户可以看到文字,但是当用户按下“更改”字样时按钮变得不确定。有什么想法吗?

我的控制器代码:

// Fictional data it wineById will be a JSON object.
$scope.wineById = {"id":"4","name":"fdfvs1","percentage":"vcxz1"}

$scope.edit = function () {
    var wine = {
        id:$scope.wineById.id,
        name:$scope.name,
        percentage:$scope.percentage
    };

    console.log($scope.name, $scope.percentage);
};

HTML:

<form novalidate ng-submit="edit()">
        <label>ID wine: <input type="text" ng-value="wineById.id" ng-model="id" ng-disabled="true"></label> <br>
        <label>Name wine: <input type="text" ng-value="wineById.name" ng-model="name"></label> <br>
        <label>Percentage wine: <input type="text" ng-value="wineById.percentage" ng-model="percentage"></label> <br>

        <input type="submit" value="Change">
</form>

案例1:

我的字段中有现有输入。按下按钮而不更改字段中的输入数据。一切都变得不明确。

案例2(有效的案例):

我的字段中有现有输入。使用不同的数据更改所有字段并按下按钮。一切都改变了。

如何解决案例1?

2 个答案:

答案 0 :(得分:1)

如果由于某种原因仍想使用ng-value,请将html更改为以下内容:

<form novalidate ng-submit="edit()">
  <label>ID wine:
   <input type="text" ng-init="id=wineById.id" ng-model="id" ng-value="wineById.id" ng-disabled="true">
  </label>
  <br>
  <label>Name wine:
    <input ng-init="name=wineById.name" type="text" ng-value="wineById.name" ng-model="name">
  </label>
  <br>
  <label>Percentage wine:
    <input ng-init="percentage=wineById.percentage" type="text" ng-value="wineById.percentage" ng-model="percentage">
  </label>
  <br>
  <input type="submit" value="Change">
</form>

更好的方法是只使用ng-model(除非你不想要双向绑定)

<form novalidate ng-submit="edit()">
    <label>ID wine:
      <input type="text" ng-model="wineById.id" ng-disabled="true">
    </label>
    <br>
    <label>Name wine:
      <input type="text" ng-model="wineById.name">
    </label>
    <br>
    <label>Percentage wine:
      <input type="text" ng-model="wineById.percentage">
    </label>
    <br>

    <input type="submit" value="Change">
</form>

Live Demo

答案 1 :(得分:0)

为什么使用ng-value,angular支持双向绑定,ng-model足以绑定数据。

<form novalidate ng-submit="edit()">
    <label>ID wine: <input type="text" ng-model="id" ng-disabled="true"></label> <br>
    <label>Name wine: <input type="text" ng-model="name"></label> <br>
    <label>Percentage wine: <input type="text" ng-model="percentage"></label> <br>

    <input type="submit" value="Change">
</form>