我怎样才能将这些NG-初始化到控制器?初始化、控制器、NG

2023-09-13 04:51:28 作者:最长情的告白i

我使用的是NG重复打印出许多食品项目的投入。我目前使用的NG-INIT初始化的输入值,就像这样:

I am using an ng-repeat to print out many food item inputs. I am currently using ng-init to initialise the values of the inputs, like so:

 <div class="formitem" ng-repeat="food in foodlist" ng-init="food.slider=0; food.unit.selected = food.unit[0];">

不过,我想要做的初始化值一些更复杂的处理。即,我想检查是否食物 foodlist 数组中已经存在 editedFood 。如果这样做,则使用存储在 editedFood 作为初始值的值。如果不是,使用0作为初始值。

However, I want to do some more complicated processing on the initialised values. Namely, I want to check if the food in foodlist already exists in the array editedFood. If it does, then use the values stored in editedFood as the initial values. If not, use 0 as the initial values.

所以,我想我需要移动此加工出来的加价,并移交给控制器,但我不明白的角度不够好,明白的地方和放大器;如何做到这一点。这NG重复控制器坐在里面FoodCtrl:

So, I guess that I need to move this processing out of the mark-up and over to the controller, but I don't understand Angular well enough to understand where & how to do this. This ng-repeat sits inside controller FoodCtrl:

myApp.controller('FoodCtrl', function ($scope, $http, $location, $anchorScroll, $filter) { }

我应该做内部FoodCtrl这INITIALISE处理?我怎么能初始化的值food.slider food.unit.selected 每个食品foodlist FoodCtrl里面?

Should I do this initialise-processing inside FoodCtrl? How can I initialise the values of food.slider and food.unit.selected for each food in foodlist inside of FoodCtrl?

更新

现在我已经尝试添加这个变化成 FoodCtrl ,无论到控制器的顶层,进入功能,没有运气:

I've now tried adding variations on this into FoodCtrl, both into the top level of the controller and into functions, with no luck:

 $scope.foodlist.food.slider = 0;

错误:类型错误:无法设置的未定义的属性'滑'

 $scope.food.slider = 0;

错误:类型错误:无法设置的未定义的属性'滑'

if ($scope.foodlist.food.slider !== undefined) {
  console.log("slider")
  $scope.foodlist.food.slider = 0;
}

错误:类型错误:无法设置的未定义的属性'滑'

$scope.foodlist.forEach(function(food) {
    food.slider = 0;
    food.unit.selected = food.unit[0];
  });

错误:'类型错误:对象#没有方法'forEach'``

Error: `TypeError: Object # has no method 'forEach'``

我感觉pretty难住了。

I'm feeling pretty stumped.

推荐答案

在你的控制器只需添加这样的事情。

In your controller just add something like this.

$scope.foodlist.forEach(function(food) {
    food.slider = 0;
    food.unit.selected = food.unit[0];
});