根据角度中的另一个字段设置输入字段的默认值

set default value of input field based on another field in Angular

本文关键字:字段 设置 输入 默认值 另一个      更新时间:2023-09-26

在 Angular (1.5) 中,我有一个包含两个输入字段的表单:

  • 身份证
  • 网址

规则:

  • 如果 ID 字段为空,则 URL 字段应为空
  • 如果 URL 字段是手动设置的,则它不应自动更改
  • 否则,URL 字段应为"http://myurl/"+ID+".txt"

我如何实现这一点?

  <input type="text" name="url"
         ng-model="url"
         ng-model-options="{ getterSetter: true }" />

    function defaulUrl() {
       if $scope.ID {
          return 'http://myurl/'+$scope.ID+'.txt';
       } 
       return ''
    }
    var _url = defaultURl();
    $scope.url = {
       url: function(url) {
            return arguments.length ? (_url= url) : defaulUrl();
       }
    }

};

在 ID 字段上使用$watch。如果 ID 字段发生更改,将调用监视函数。

$scope.$watch('$scope.ID', function() {
    $scope.url = 'http://myurl/' + $scope.ID + '.txt';
}, true);
这是我

制作的符合您要求的小提琴:小提琴

代码

//HTML
<div ng-app="myApp" ng-controller="MyController">
    ID <input type="text" ng-model="data.id" ng-change="onIDChange()"/>
    URL <input type="text" ng-model="data.url" ng-change="onManualUrlChange()"/>
</div>
//JS
angular.module('myApp',[])
.controller('MyController', ['$scope', function($scope){
  $scope.data = {
    id:'',
    url:''
  }
  $scope.manualUrl = false;
  $scope.onIDChange = function(){
    if(!$scope.manualUrl){
      if($scope.data.id === ''){
        $scope.data.url = '';
      } else {
        $scope.data.url = "http://myurl/" + $scope.data.id + ".txt";
      }
    }
  }
  $scope.onManualUrlChange = function(){
    $scope.manualUrl = true
  };
}]);