Question

looking for some ideas here. i have a meal plan object that contains an array of meals. only one meal can be set as primary at a time but i want the user to be able to cycle through the array of meals and mark a meal as primary. i am stuck trying to figure out if ngrepeat makes sense here or ngswitch or ngshow. any thoughts or samples would be highly appreciated!

I have tried multiple approaches with no luck. thanks

Was it helpful?

Solution

You could cycle through the meals by index of the meal and have a button to choose the meal like this:

http://jsfiddle.net/c6RZK/

var app = angular.module('mealsApp',[]);

app.controller('MealsCtrl',function($scope) {
    $scope.meals = [
        {name:'Meatloaf'},
        {name:'Tacos'},
        {name:'Spaghetti'}
    ];

    $scope.meal_index = 0;
    $scope.meal = {};

    $scope.next = function() {
        if ($scope.meal_index >= $scope.meals.length -1) {
            $scope.meal_index = 0;
        }
        else {
            $scope.meal_index ++;
        }
    };

    $scope.choose = function(meal) {
        $scope.meal = meal;
    }
});

HTML

<div ng-app="mealsApp" ng-controller="MealsCtrl">
    <div ng-repeat="m in meals">
        <div ng-if="meal_index == $index">
            <strong>{{m.name}}</strong>
            <button ng-click="choose(m)">Choose</button>
        </div>
    </div>
    <hr>
    <button ng-click="next()">Next</button>
    <hr>Your Choice: {{meal.name}}
</div>

OTHER TIPS

You could just attach a property to the plan, with a flag that says whether or not it's the primary plan.

Here's a sample implementation:

  $scope.plans = [{name:"One"}, {name:"Two"}, {name:"Three"}];

  $scope.selectPlan = function(plan) {        
    for(var i = 0, l = $scope.plans.length; i < l; i++) {
      $scope.plans[i].primary = false;
      if($scope.plans[i] === plan) {
        $scope.plans[i].primary = true;
      }
    }
  };

HTML:

<ul>
  <li ng-click="selectPlan(plan)" ng-repeat="plan in plans" ng-class="{primary: plan.primary}"><a href>{{plan.name}}</a></li>
</ul>

If you'd rather not attach properties you could use something like a selected index property on your controller.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top