Skip to content Skip to sidebar Skip to footer

Why Does This Ng-click Work With A Function, But Not With These Values?

I have the following html:

Solution 1:

Because ng-repeate create new scope and myValue is out of scope. so if you are using controllerAs syntax it works correctly.

var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope) {
  var vm = this;
  vm.valueList = [{
    key: "A"
  }, {
    key: "B"
  }];
  vm.myValue = vm.valueList[0].key;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="AppCtrl as vm">
  <div class="btn-group">
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
        {{vm.myValue}} 
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu">
      <li ng-repeat="value in vm.valueList">
        <button class="btn btn-link" ng-click="vm.myValue = value.key">
                {{value.key}}
            </button>
      </li>
    </ul>
  </div>
</div>

Post a Comment for "Why Does This Ng-click Work With A Function, But Not With These Values?"