【问题标题】:angularjs add white space in ng-modelangularjs 在 ng-model 中添加空格
【发布时间】:2017-07-10 09:18:23
【问题描述】:

我有这个<input name="Name" type="text" id="Name" class="step-input" placeholder="NAME*" readonly="readonly" ng-model="(ContactPerson)+(ContactPersonSurname)" /> 在 ng-model 上,它连接了两个字段并且工作正常,但我想使用 angular 在 (ContactPerson) 和 (ContactPersonSurname) 之间添加空格。我怎样才能做到这一点?

【问题讨论】:

    标签: angularjs-directive angularjs-ng-model


    【解决方案1】:

    如果您在 ng-model 指令中提供表达式,您将收到 [ngModel:nonassign] 错误,在 Angularjs documentation 他们明确指出

    当 ngModel 指令绑定到的表达式是不可赋值的表达式时,会发生此错误。
    始终确保可以分配通过 ngModel 指令绑定的表达式。

    解决方案:
    创建一个新的 $scope 变量,类似于
    $scope.fullName = (ContactPerson)+ ' ' +(ContactPersonSurname);,然后在您的 html 中使用它,如下所示。

    angular.module('mainApp', [])
        .controller('mainCtrl', function ($scope) {
           $scope.name = "john";
          $scope.surName = "Doe";
          $scope.fullName = $scope.name + " " + $scope.surName;
        });
    <html ng-app="mainApp">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    </head>
    <body ng-controller="mainCtrl">
      <input type="text" ng-model="fullName" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
    </body>
    </html>

    【讨论】:

      【解决方案2】:

      您的输入字段是只读的。所以你可以使用表达式代替绑定模型。

      var myApp = angular.module('myApp',[]);
      
      function MyCtrl($scope) {
          $scope.ContactPerson = 'foo';
          $scope.ContactPersonSurname = 'bar';
      }
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
      
      <div ng-app="myApp">
      
      <div ng-controller="MyCtrl">
        <input name="Name" type="text" id="Name" class="step-input" readonly="readonly" value="{{ContactPerson}} {{ContactPersonSurname}}"  />
      </div>
      </div>

      希望这能解决您的问题。

      【讨论】:

        猜你喜欢
        • 2018-06-21
        • 1970-01-01
        • 1970-01-01
        • 2017-11-19
        • 2014-12-16
        • 2023-04-04
        • 2015-07-14
        • 1970-01-01
        • 2019-08-06
        相关资源
        最近更新 更多