我是Angular的新手,我仍在学习正确的做事方式(我意识到这不是它!)。目前,我有一系列对象(在这种情况下是成分)。每种成分都有不同的营养成分,每种营养素都有不同的测量数据(一些tsp,oz等等,其他一些切片,一个立方体等)。这些测量中的每一个都具有与它们相关联的乘数以用于计算。
当我点击单个成分时,它被添加到一系列成分对象中。这个新的成分列表填充了一个成分列表(配方),其中我在选择/选项中包含每个成分测量值以及接受数量的输入。我需要能够动态获取输入的数量和每种成分的测量值,以便我可以计算每种成分的各种营养素,然后计算整个配方。我将组合营养价值保存在一个数组中,并不担心保存个人计算。然后我想将数量,测量和成分保存到单独的数组(配方)。
我可以使用单个项目,但多个项目是一个挑战。
这是来自控制器。添加成分从完整的成分列表中调用:
$scope.addIngredient = function(ndb,name,nutrients){
var id = $scope.recipe.ingredients.length +1;
//$scope.recipe.ingredients is where I'm saving the individual ingredients
$scope.measure = nutrients[0].measures;
//each ingredient includes a property called measures for each
// nutritional item (ie vitamin A, Protein, etc).
//each of these is arrays is identical for a single ingredient, so I
//just grabbed the first.
var measurement = nutrients[0].measures;//I changed the following code
// to this because $scope.measurement was assigning all of my selects
//to the same thing.
$scope.measurement = nutrients[0].measures;
// this worked to assign the model for single ingredients, but not
//multiple, I've been throwing a bunch of stuff at the wall and have
//kept this as an example
$scope.recipe.ingredients.push({
id: id,
name: name,
ndbno: ndb,
nutrients: nutrients,
measures: measurement
})
//This is how Im currently storing the each recipes ingredient.
};
$scope.convertToNumber = function(){
//This is called when on selects ng-change, measureMultiplier is used
//to calculate each ingredient according to its selected measurement.
//measurement.eqv should gets it's value from the selected option
// Presently it gets called but is undefined.
$scope.measureMultiplier = ($scope.measurement.eqv);
};
$scope.qty = 1; //The number of a particular ingredient pre-populated to 1
$scope.recipe.totalled = []; //This is where I will store the combined
//nutritional values for each recipe.
这是在html中:
<single-ingredient ingredient="recipe.ingredients"
qty="qty" measurement="measurement"
on-change="convertToNumber()"
on-remove="removeIng(id)">
</single-ingredient>
我现在不使用on-remove。
这是我目前的指令,我确信这是大部分问题所在。它的一些工作和视觉上它的运作。但当它触发ng-change时,它是未定义的。此外,ingredient[{{item.id -1}}].measures
抓取正确的信息,但如果我删除了该成分,它就会搞砸了。再加上一团糟。
.directive('singleIngredient',[ function(){
return {
scope: {
ingredient : '=',
qty : '=qty',
measurement : '=measurement',
'removeIng': '&onRemove',
'convertToNumber': '&onChange'
},
restrict: "AE",
transclude: true,
template: ' <ul><li ng-repeat="item in ingredient" >' +
'<input ng-model="qty" size="4" >{{item.name}}' +
'<select ' +
'ng-options="item.label for item in ingredient[{{item.id - 1}}].measures" ' +
'ng-model="measurement" ' +
'ng-change="convertToNumber()">' +
'</select>' +
'<span</span>' +
'</li></ul>'
}
同样,最终,我需要在变化时获取数量,并在选择/选项列表中的值与其相关成分(通过id或类似)一起变化时获取。如果有人能指出我正确的方向,我愿意做腿部工作。谢谢!