内容简介:翻译自:https://stackoverflow.com/questions/25881804/angularjs-passing-params-from-controller-to-service
我在弄清楚如何将角度控制器中的参数传递给我时遇到了麻烦
服务
#my controller
'use strict';
angular.module('recipeapp')
.controller('recipeCtrl', ['$scope', 'recipeService',
function($scope, recipeService){
$scope.recipeFormData={};
$scope.recipeSave = function(){
recipeService.saveRecipe();
}
}]);
#my service
'use strict';
angular.module('recipeapp').service('recipeService',['$http', function($http){
this.saveRecipe = save;
function save(callback){
//calling external http api
}
}]);
我在这里要做的是,从我的表单获取$scope.formData并且控制器应该将其传递给服务,根据我的理解,我不能在服务中使用$scope所以我需要找到一种传递$的方法scope.formData到服务
艰难的想法,在控制器中,recipeService.saveRecipe($scope.formData);但我不确定如何从服务中收集,
当我更改服务this.saveRecipe(val)= save;它不起作用:(
任何帮助都会得到满足
此示例演示了角度应用程序的正确结构:
>控制器内的模型初始化
>实现服务单例,并注入您的控制器
>使用$http promises异步调用Web API调用,并允许服务的调用者处理其成功/失败.
>使用“控制器作为”语法从控制器公开函数,而不是直接从作用域公开函数.
>双向数据模型绑定(文本框到配方和配方到文本框)
在控制器中初始化模型:
angular.module('recipeapp')
.controller('recipeCtrl', ['$scope', 'recipeService',
function($scope, recipeService){
// initialize your model in you controller
$scope.recipe={};
// declare a controller function that delegates to your service to save the recipe
this.saveRecipe = function(recipe) {
// call the service, handle success/failure from within your controller
recipeService.saveRecipe(recipe).success(function() {
alert('saved successfully!!!');
}).error(function(){
alert('something went wrong!!!');
});
}
}]);
在配方服务中,定义saveRecipe函数:
angular.module('recipeapp').service('recipeService',['$http', function($http){
// expose a saveRecipe function from your service
// that takes a recipe object
this.saveRecipe = function(recipe){
// return a Promise object so that the caller can handle success/failure
return $http({ method: 'POST', url: '/api/recipe/add', data: recipe});
}
}]);
将食谱对象绑定到视图中;添加一个按钮来调用saveRecipe控制器功能并保存配方(传入模型配方对象):
<div ng-app="recipeapp" ng-controller="recipeCtrl as ctrl">
<form name="recipeForm">
Recipe Name: <input type="text" ng-model="recipe.name" />
<button ng-click="ctrl.saveRecipe(recipe)">Save Recipe</button>
</form>
</div>
翻译自:https://stackoverflow.com/questions/25881804/angularjs-passing-params-from-controller-to-service
以上所述就是小编给大家介绍的《AngularJS:将params从控制器传递到服务》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- iOS之导航返回上上个控制器或指定返回某个控制器
- iOS小技巧·把子视图控制器的视图添加到父视图控制器
- javascript – AngularJS控制器错误 – :$http.get不是控制器部分的函数
- AC敏捷控制器及准入控制技术对比
- angularjs – 使用ui-router时,控制器是否可以从父控制器继承范围
- SpringMVC: 前端控制器
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
程序员成长的烦恼
吴亮、周金桥、李春雷、周礼 / 华中科技大学出版社 / 2011-4 / 28.00元
还在犹豫该不该转行学编程?还在编程的道路上摸爬滚打?在追寻梦想的道路上你并不孤单,《程序员成长的烦恼》中的四位“草根”程序员也曾有过类似的困惑。看看油田焊接技术员出身的周金桥是如何成功转行当上程序员的,做过钳工、当过外贸跟单员的李春雷是如何自学编程的,打小在486计算机上学习编程的吴亮是如何一路坚持下来的,工作中屡屡受挫、频繁跳槽的周礼是如何找到出路的。 《程序员成长的烦恼》记录了他们一步一......一起来看看 《程序员成长的烦恼》 这本书的介绍吧!
随机密码生成器
多种字符组合密码
HTML 编码/解码
HTML 编码/解码