如何自动填充angularjs中的输入字段?

时间:2019-01-20 18:28:56

标签: javascript angularjs

我只想通过插入名字和姓氏输入框来填充全名输入框。我只是将输入框中两个值以上的数据绑定在一起,但不会在全名输入框中显示该数据。提前致谢!! 代码:

                <div ng-app="myApp" ng-controller="myCtrl">

                First Name: <input type="text" ng-model="firstName"><br>
                Last Name: <input type="text" ng-model="lastName"><br>
                Full Name:<input ng-bind="firstName+" "+lastName>

                    <script>
      var app = angular.module('myApp', []);
      app.controller('myCtrl', function($scope) {
      $scope.firstName = "John";
      $scope.lastName = "Doe";
      });
       </script>

2 个答案:

答案 0 :(得分:1)

您不能将ng-bind指令用于HTML属性,请参见documentation

ng-bind可以在其他HTML标签中使用:

<span ng-bind="firstName + ' ' + lastName"></span>

通过input标签,您可以使用以下指令:

<input type="text"
       ng-model="string"
       [name="string"]
       [required="string"]
       [ng-required="string"]
       [ng-minlength="number"]
       [ng-maxlength="number"]
       [pattern="string"]
       [ng-pattern="string"]
       [ng-change="string"]
       [ng-trim="boolean"]>

但是,您可以在HTML value属性中使用花括号符号:

<input value="{{firstName + ' ' + lastName}}">

类似这样的东西:

(function() {
  var app = angular.module("myApp", []);
  app.controller("myCtrl", function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
  });
}());
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

  First Name: <input type="text" ng-model="firstName"><br> Last Name: <input type="text" ng-model="lastName"><br> Full Name: <input value="{{firstName + ' ' + lastName}}">
  <span ng-bind="firstName + ' ' + lastName"></span>
</div>

答案 1 :(得分:0)

     <div ng-app="myApp" ng-controller="myCtrl">

            First Name: <input type="text" ng-model="firstName"><br>
            Last Name: <input type="text" ng-model="lastName"><br>
            Full Name:<span ng-bind="fullName"></span>
     </div>

     <script>
          var app = angular.module('myApp', []);
          app.controller('myCtrl', function($scope) {
          $scope.firstName = "John";
          $scope.lastName = "Doe";
          $scope.fullName =  $scope.firstName  + " " + $scope.lastName;
       });
     </script>