user2633328
user2633328

Reputation: 57

Need help on simple data binding that mysteriously gone away randomly(no controller, only pure html and AngularJS)

I have simple html to try AngularJS databinding. When I enter text in input, the label below it binds correctly, and displays data.country. However, when I use backspace to delete text until it is gone, and try to reenter text again, nothing show up on the bound span. The problem seems random, since if I keep repeating this (enter text, delete, enter text) sometimes it shows up, sometimes it doesn't

Here is the fiddle http://jsfiddle.net/supatwo/eMfNp/

At first glance, I thought it was random, but in fact it is always a pattern. 1. Enter text,e.g. "abcde". This binds correctly to span below input box. 2. Backspace until text is gone. 3. Re enter text, e.g. 12345. Bug? Nothings show up in span below input box. 4. Backspace until text is gone. 5. Enter some text, now it shows up correctly, and this keep repeating (steps 1-5).

I use batarang to check but here it only has $rootScope, and batarang shows no model in $rootScope. If I put model in a controller, then there is no issue.

<!doctype html>
<html lang="en" ng-app>
<head>
  <meta charset="utf-8">
  <title>My HTML File</title>
  <link rel="stylesheet" href="css/app.css">
  <link rel="stylesheet" href="css/bootstrap.css">
  <script src="lib/angular/angular.js"></script>
  </head>
<body>
  country name: <input type="text" ng-model="data.country"></input>
   <br/><span class="label"> {{data.country}}</span> <br/>
</body>
</html>

Upvotes: 0

Views: 176

Answers (1)

Denison Luz
Denison Luz

Reputation: 3565

Take a look at this code (http://jsfiddle.net/denisonluz/9mFpp/245/). It is working.

<!doctype html>
 <html lang="en" ng-app="myApp">
 <head>
   <meta charset="UTF-8">
   <title>Document</title>

   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>

   <script>

   var myApp = angular.module('myApp', [])
       .controller('MainCtrl', function($scope) {
          $scope.data = {country: 'Brazil'};

          $scope.set = function(new_country) {
              this.data.country = new_country;
          }
      });

   </script>

  </head>
  <body>


    <div ng-controller="MainCtrl">
      <input name="data.country" ng-model="data.country"><br />
       <span>{{data.country}}</span><br />
       <button ng-click="set('Italy')">set to Italy</button>      
    </div>

    </body>
    </html>

About the issue you are facing, the only thing I could think of is that you should define your model in the controller, not in the view. (https://stackoverflow.com/a/10612424/1310945)

Upvotes: 0

Related Questions