Why does this ng-click work with a function, but not with these values?

百般思念 提交于 2019-12-12 18:06:53

问题


I have the following html:

<div class="btn-group">
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
        {{myValue}} 
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu">
        <li ng-repeat="value in valueList">
            <button class="btn btn-link" ng-click="myValue = value.key">
                {{value.key}}
            </button>
        </li>
   </ul>
</div>

In the controller:

$scope.valueList = [ { key: "A" }, { key: "B" } ];
$scope.myValue = $scope.valueList[0].key;

This returns a dropdown starting with "A" with "A" & "B" being options.

Now, the above html will NOT turn myValue into "B", when the dropped-down button is clicked. However, when I change the ng-click into ng-click="changeValue(value.key)" it does work as expected. Why does the myValue = value.key do nothing while {{ value.key }} shows the right things?

Function for completeness:

$scope changeValue = function(valueKey) { 
    $scope.myValue = valueKey 
}

回答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>


来源:https://stackoverflow.com/questions/45593879/why-does-this-ng-click-work-with-a-function-but-not-with-these-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!