wivku
wivku

Reputation: 2643

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

In Angular (1.5) I have a form with two input fields:

The rules:

How do I achieve this?

Upvotes: 0

Views: 1019

Answers (3)

ziaulain
ziaulain

Reputation: 94

Use $watch on ID Field. If the ID field is changed, the watch function will be called.

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

Upvotes: 0

George Chen
George Chen

Reputation: 6939

  <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();
       }
    }

};

Upvotes: 1

Gabs00
Gabs00

Reputation: 1877

Here is a fiddle I made that meets your requirments:fiddle

The code

//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
  };
}]);

Upvotes: 0

Related Questions