0

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

  • ID
  • URL

The rules:

  • If the ID field is empty then the URL field should be empty
  • If the URL field is manually set then it should not change automatically
  • Otherwise the URL field should be "http://myurl/"+ID+".txt"

How do I achieve this?

3 Answers 3

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

};

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

i don't think this will work. "If the URL field is manually set then it should not change automatically". Changing ID will overwrite the manually inputted URL
Agreed, how will this care for not changing the url if it is manually entered?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.