我正在使用 Angular.js 迈出第一步,但我遇到了一个我不知道如何处理 Angular 的小问题。我知道很多 jQuery 方法来解决它,但我确信它可能存在 Angular 方式:
首先,我将一个选择元素设置为 currentPlant
作为 ng-model
<select class="form-control" name="planta" ng-model='currentPlant' ng-options='plant.name for plant in plants' >
</select>
我将当前名称打印为页面标题,当我更改所选值时我看到此元素更新,因此我确信 currentPlant
正在正确更新。
<h1>{{ currentPlant ? currentPlant.name : 'Seleccione una planta'}}</h1>
现在我有以下按钮:
<button class='btn btn-primary' ng-click='loadTowers()'>
Cargar torres
</button>
当按下按钮时,loadTowers
函数被执行,现在是问题开始的时候。我以这种方式在 Controller 中设置了 loadTowers
函数:
$scope.loadTowers = plants.towers;
plant
是一个 Angular 服务,它在内部实现了 towers
功能。我需要在此函数中获取 currentPlant
的值。看一看:
.factory('plants', ['$http',function($http){
var o = {
plants: [],
towers : []
};
o.towers = function(){
var id = ¿?; // I NEED SET THIS VARIABLE WITH THE currentPlant.id VALUE
$http.get('/api/v1/plants/'+id+'/towers')
.success(function(data){
angular.copy(data, o.towers);
})
}
return o;
}]);
我可以在 option 元素中设置一个 data-plant
属性,并通过 jQuery 获取选择,但我试图避免这种解决方案。你如何处理这个问题?
注意:考虑到我只是想在按下按钮时选择选项
并向API发出不同的get
请求`通过服务发挥作用。
提前致谢。
最佳答案
在 ngclick 中传递值:
<button ng-click='loadTowers(currentPlant)'>
然后在工厂参数中添加:
o.towers = function(currentPlant){
}
关于javascript - 在 Angular.js 工厂中获取外部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39442010/