methuselah
methuselah

Reputation: 13206

ng-model not updating when select dropdown is updated

Why is it that when I change my select option in header.html (which has been included in index.html as follows:

<div ng-include="'views/templates/header.html'"></div>

for some reason the change doesn't propagate to where {{ vm.selectedCurrency }} is called in main.html. Why is this the case?

header.html

<header class="header-style-2" ng-controller="MainController as vm">
  <select class="selectpicker" ng-model="vm.selectedCurrency" ng-options="o as o for o in vm.currencyTypes" ></select>
</header>

main.html

  <div class="popular_product">
    <ul class="row">             
      <!--  New Arrival  -->
      <li class="col-sm-3" ng-repeat="product in vm.menNewArrivals">
        <div class="items-in"> 
          <!-- Image --> 
          <img ng-src="{{ product.image }}" style="height:400px; width: auto;"> 
          <!-- Hover Details -->
          <div class="over-item">
            <ul class="animated fadeIn">
              <li><a href=""><i class="fa fa-info"></i></a></li>
              <li><a href=""><i class="fa fa-retweet"></i></a></li>
              <li><a href=""><i class="fa fa-heart-o"></i></a></li>
              <li class="full-w"> <a href="#." class="btn">ADD TO CART</a></li>
            </ul>
          </div>
          <!-- Item Name -->
          <div class="details-sec">
            <a href="#">{{ product.name }}</a> 
            <span class="font-montserrat">
              {{ product.price }} {{ vm.selectedCurrency }}
            </span> 
          </div>
        </div>
      </li>
    </ul>
  </div>

main-controller.js

vm.menNewArrivals = {};
vm.currencyTypes = MainService.getCurrencyTypes();
vm.selectedCurrency =  vm.currencyTypes[0];

MainService.getMenNewArrivals().then(function(result) {
  vm.menNewArrivals = result.data.menNewArrivals;
});

main-service.js

function getCurrencyTypes()
{
  var currencyTypes = ['GBP', 'USD', 'EUR'];
  return currencyTypes;
}

Upvotes: 1

Views: 37

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

There could be two way to solve this problem.

  1. You're already using ng-controller="MainController as vm", your header html have its own ng-controller, which is creating an another instance of MainController again. That mean header has its own scope, different than the main.html's MainController controller and selected value gets stored in new controller instance. Removing ng-controller from header.html would fix your issue, by removing it header html will have access to main html controller scope.
  2. If above is not the reason, you can create an service to share data between different component's of Angular application. In this case selectedCountry would be saved in shareable data service.

Upvotes: 1

Related Questions