KevinTale
KevinTale

Reputation: 1858

Use scope variable in ng-repeat

I want to use a $scope variable within the ng-repeat attribut, like so :

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

But it doesnt seem to work, {{usersOpinion}} remains non-interpreted... How could I manage to make it work?

The Idea is to dynamically change {{usersOpinion}} when clicking on button.

Thanks

Upvotes: 0

Views: 1330

Answers (4)

Jasmin Kurtic
Jasmin Kurtic

Reputation: 141

if I'm understand your question, you can try this

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"
  }];
});
<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>

Upvotes: 0

Aleksandar Gajic
Aleksandar Gajic

Reputation: 1359

If you want to change it dynamically you need to add ng-click to div tag, something like this

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

and add function to scope

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

no you can do whaterver you want with value of that opinion, here is the whole code with both simple array of opinions and objects http://jsfiddle.net/Lvc0u55v/9513/

Upvotes: 0

Venkat
Venkat

Reputation: 265

Instead of ng-repeat="userOpinion in {{usersOpinion}}" ,change it to ng-repeat="userOpinion in usersOpinions.

You should use like

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

Upvotes: 1

Hykalos
Hykalos

Reputation: 51

It should be enough to remove the curly brackets. The ng-repeat is interpreted as code.

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

The curly brackets tells angular that it should transform the variable into a string before outputting it.

Upvotes: 0

Related Questions