在ng-repeat中使用范围变量

时间:2016-09-14 09:04:09

标签: angularjs

我想在ng-repeat attribut中使用$ scope变量,如下所示:

<div class="userOpinion" ng-if="usersOpinions.length != 0" ng-repeat="userOpinion in {{usersOpinion}}">

但它似乎不起作用,{{usersOpinion}}仍然没有解释......我怎么能设法使它工作?

想法是在点击按钮时动态更改{{usersOpinion}}。

由于

4 个答案:

答案 0 :(得分:1)

而不是ng-repeat="userOpinion in {{usersOpinion}}",将其更改为ng-repeat="userOpinion in usersOpinions

您应该使用

<div class="userOpinion" ng-if="usersOpinions.length != 0" ng-repeat="userOpinion in usersOpinions">{{userOpinion}}</div>

答案 1 :(得分:0)

删除大括号应该足够了。 ng-repeat被解释为代码。

<div class="userOpinion" ng-if="usersOpinions.length != 0" ng-repeat="userOpinion in usersOpinion">

花括号告诉angular它应该在输出之前将变量转换为字符串。

答案 2 :(得分:0)

如果你想动态更改它,你需要添加ng-click到div标签,类似这样的

  <div class="userOpinion" ng-if="usersOpinions.length != 0" ng-repeat="userOpinion in usersOpinion" ng-click="changeOpinion($index)">
    {{userOpinion}}
  </div>

并将功能添加到范围

$scope.changeOpinion = function (index) {
    $scope.usersOpinion[index] += '1';
}

不,你可以用这个意见的价值来做你想要的,这里是整个代码,包含简单的意见和对象http://jsfiddle.net/Lvc0u55v/9513/

答案 3 :(得分:0)

如果我理解你的问题,你可以试试这个

&#13;
&#13;
var autoDrops = angular.module('autoDrops', []);
autoDrops.controller('DropsController', function($scope) {
  $scope.usersOpinion = [];

  $scope.datas = [{
    "name": "item01"
  }, {
    "name": "item02"
  }, {
    "name": "item03"
  }, {
    "name": "item04"
  }, {
    "name": "item05"
  }, {
    "name": "item06"
  }];
  $scope.datas1 = [{
    "name": "item11"
  }, {
    "name": "item12"
  }, {
    "name": "item13"
  }, {
    "name": "item14"
  }, {
    "name": "item15"
  }, {
    "name": "item16"
  }];
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="autoDrops" ng-controller="DropsController">
  <button ng-click="usersOpinion = datas">
    data
  </button>
  <button ng-click="usersOpinion = datas1">
    datas1
  </button>
  <div>
    <div ng-repeat="elem in usersOpinion">
      {{elem}}
    </div>
  </div>
</div>
&#13;
&#13;
&#13;