Thomas Murphy
Thomas Murphy

Reputation: 1468

AngularJS ng-repeat: view doesn't update on model change…

I am attempting to add items to my view via ng-submit. The function getTemp works as expected, and $scope.temperatures is properly updated (I can see it in the console), however the new data values do not appear in the view. I am unsure what is not being properly bound.

I've looked through the other related questions here, but none seem to be quite the same.

VIEW:

<div ng-controller="tempCtrl" class="container">
        <form id="zipCodeForm"  ng-submit="submit()" ng-controller="tempCtrl">
            <input id="zipCodeInput" ng-model="text" name="text" type="text"> </input>
            <input id="zipSubmit" type="submit" value="Submit" class="btn btn-large btn-primary"></input>
        </form>

        <div>
            <h4 ng-repeat='item in temperatures'>
                Zip code is {{item.zip}} and temperature is {{item.temp}}
            </h4>
        </div>
    </div>  

MODEL:

var temperatureApp = angular.module('temperatureApp', []);

temperatureApp.controller('tempCtrl', function ($scope, $http) {
$scope.temperatures = [
                    {zip: "10003", temp: "43"},
                    {zip: "55364", temp: "19"}
];  

function getTemp(zipCode){
    $http({method: 'GET', url: 'http://weather.appfigures.com/weather/' + zipCode}).
    success(function(data){
        tempObject = data;
        $scope.temperatures.push({zip: "10003", temp: tempObject.temperature.toString()});
    });
}

$scope.submit = function() {
    getTemp(this.text);
    console.log($scope.temperatures);
}

})

Upvotes: 1

Views: 14606

Answers (1)

Khanh TO
Khanh TO

Reputation: 48972

The problem is you have ng-controller="tempCtrl" in your form. This will create its own child scope of the current scope. Therefore any object you put into this scope will not affect the current scope. Try removing it:

 <div ng-controller="tempCtrl" class="container">
     <form id="zipCodeForm" ng-submit="submit()"> //remove your redundant ng-controller
         <input id="zipCodeInput" ng-model="text" name="text" type="text"> </input>
         <input id="zipSubmit" type="submit" value="Submit" class="btn btn-large btn-primary"></input>                  
     </form>
     <div>
          <h4 ng-repeat='item in temperatures'>
              Zip code is {{item.zip}} and temperature is {{item.temp}}
          </h4>
     </div>
</div>

DEMO

Upvotes: 6

Related Questions