AngularJS:将params从控制器传递到服务
发布时间:2020-12-17 07:20:52 所属栏目:安全 来源:网络整理
导读:我在弄清楚如何将角度控制器中的参数传递给我时遇到了麻烦 服务 #my controller 'use strict';angular.module('recipeapp') .controller('recipeCtrl',['$scope','recipeService',function($scope,recipeService){ $scope.recipeFormData={}; $scope.recipeS
我在弄清楚如何将角度控制器中的参数传递给我时遇到了麻烦
服务 #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;它不起作用:( 任何帮助都会得到满足
此示例演示了角度应用程序的正确结构:
>控制器内的模型初始化 在控制器中初始化模型: angular.module('recipeapp') .controller('recipeCtrl',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',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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |