0

I am stuck on getting value back after I call a function in my HTML file. I did some research and tried could things but no success. Please see below code:

HTML:

<div class="form-group">
    <div class="col-sm-9"><label for="IPAddr">IP Address</label><input  ng-model="IPAddr" id="IPAddr" name="IPAddr" ng-blur="IPAvail=validateIP()"           
     type="text" class="form-control">{{IPAvail}}</div>          
  </div> 

A basic form with an input field for IP address. Calls the validateIP(), and shows returned value "{{IPAvail}}".

JS:

$scope.validateIP = function(IPAvail) {
    $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
    var ipVar = $.param({ip: $scope.ipadd});
    $http({
        url: 'https://test.com/flask_server/findIP',
        method: "POST",
        data: ipVar
    })
    .then(function(response) {     
        $scope.result = response.data;
        ip = response.data;     

         if (ip.indexOf("10.10.10.1") >=0) {
            alert("Matches with IP")
            IPAvail = "Yes"
            return IPAvail
        } else {
            alert("Does not match with IP")
        }
        IPAvail = "No"
        return IPAvail
});
};

I simplified the code to make it easy to read but basically, everything is working correctly but the only thing I am having an issue is returning IPAvail variable back to HTML so it can be used here:

type="text" class="form-control">{{IPAvail}}</div> 

Thanks Damon

3
  • Instead of returning IPAvail, set $scope.IPAvail to the required value. Rather than use onblur, you should defer to ng-change="validateIP()" Commented Mar 19, 2018 at 22:37
  • That did the trick .. thanks!!!! i see it works with ng-blur as well, just for info can you please explain why I should use ng-change instead of blur? Commented Mar 19, 2018 at 22:42
  • I explained in the answer. Please let me know if you need further clarification. Please accept my answer. Commented Mar 19, 2018 at 22:44

1 Answer 1

1

Instead of returning IPAvail, set $scope.IPAvail to the required value. Rather than use onblur, you should defer to ng-change="validateIP()".

Using ng-change allows AngularJS to know about the effect. Otherwise you may run into trouble with AngularJS not knowing. It is better for AngularJS to know.

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

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.