This example demonstrates the correct structure of an angular application:
- Initializing a model inside your controller
- Implement singleton service and insert into your controller
- Using $ http promises to asynchronously invoke the web API and provide callers with your services the ability to handle their success / failure.
- Using the controller-like syntax to expose functions from your controller, rather than displaying functions directly from the scope.
- Binding two-way data binding (text field for recipe and recipe for text field)
Initialize your model in your controller:
angular.module('recipeapp') .controller('recipeCtrl', ['$scope', 'recipeService', function($scope, recipeService){
In the recipe service, define the saveRecipe function:
angular.module('recipeapp').service('recipeService',['$http', function($http){
Link your recipe to your view; add a button to call the controller function saveRecipe and save the recipe (going through the model's recipe object):
<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>
source share