sam*_*207 8 angularjs angularjs-service angularjs-scope angularjs-controller
我在上搞清楚如何从我的传递参数的麻烦angular
controller
来
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
}
}]);
Run Code Online (Sandbox Code Playgroud)
我在这里尝试做的是,$scope.formData
从我的表单和控制器获取应该传递给service
,根据我的理解,我不能$scope
在里面使用service
所以我需要找到一种传递$scope.formData
给服务的方式
在控制器中,强硬的想法会是,recipeService.saveRecipe($scope.formData);
但我不确定如何从服务中收集,
当我改变服务this.saveRecipe(val) = save;
它不起作用:(
任何帮助都会得到满足
pix*_*its 19
此示例演示了角度应用程序的正确结构:
在控制器中初始化模型:
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!!!');
});
}
}]);
Run Code Online (Sandbox Code Playgroud)
在配方服务中,定义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});
}
}]);
Run Code Online (Sandbox Code Playgroud)
将食谱对象绑定到视图中; 添加一个按钮以调用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>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28802 次 |
最近记录: |