0

I have this weird, weird issue.

  1. I apply ng-model to my input
  2. I hit Get IP
  3. I set the controller's property to match the ng-model
  4. The input should update

This is what SHOULD happen. However, I have a weird issue, where the data binding won't get updated, until I unfocus/blur the input.

https://jsfiddle.net/941d7qat/

var app = angular.module('app', []);
app.controller('Controller', function() {
    this.ip = "";

    $("#getIP").on("click", () => {
        $.get("https://api.ipify.org/?format=json", (response) => {
            this.ip = response.ip;
        });
    });
});

I've worked with AngularJS for a few months now (although with TypeScript) and I've never experienced this before. I can see

MortenMoulder
  • 6,138
  • 11
  • 60
  • 116

1 Answers1

4

There are multiple issues

  1. Don't do dom stuff in your controller, angular already provides to ways to add click event and do ajax. So don't mix jQuery and angular code.
  2. In your code the scope is not updated in a digest cycle that is why the input value is not getting updated

So

var app = angular.module('app', []);
app.controller('Controller', ['$http',
  function($http) {
    this.ip = "";

    this.getIP = () => {
      $http.get('https://api.ipify.org/?format=json').success((response) => {
        this.ip = response.ip;
      })
    }

  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<div ng-app="app" ng-controller="Controller as vm">
  <input type="text" ng-model="vm.ip" id="ip" />
  <button id="getIP" ng-click="vm.getIP()">Get IP</button>
  <br />
  <p>TEST: {{vm.ip}}</p>
</div>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531