Web888.vn
  • Shop
  • Blog
Đăng nhập
  • Đăng nhập / Đăng ký

Please enter key search to display results.

Home
  • AngularJS
  • AngularJS
  • Javascript Programming
Factory and Service in angularJS

Factory and Service in angularJS

  • 25-07-2022
  • Toanngo92
  • 0 Comments

In addition to using providers to create services, AngularJS implements ideas through a business architecture (services). AngularJs provides 2 functions to create services:

  • factory()
  • service()

Mục lục

  • Factory
  • Service
    • Difference between Service and Factory

Factory

A factory is a reusable, value-returning method that performs tasks such as validation, or business rules, the factory generates the desired values when the controller or service needs it. These generated values can be reused for contrrollers or services whenever needed

The factory() method is a function, it creates a factory object and returns that object, so it’s not the same as the value generated from the value() method I described above, the factory uses a function to help do this. more complex operations like value calculation… build logic that returns value, then returns value and can inject similar to value() method

Factory example

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Example Factory</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.js"></script> <style> input, select { margin-bottom: 10px; } </style> </head> <body ng-app="myApp"> <div ng-controller="myCtrl"> <h1>Calculate total product</h1> Product price: <br /> <input type="number" ng-model="price" /> <br /> Shipping type: <br /> <select ng-model="shippingtype"> <option value="flat">Flat shipping - 10$</option> <option value="custom">Express - custom price</option> </select> <br /> <input type="number" ng-model="shipping" ng-show="shippingtype == 'custom'" /> <br /> <p>Total: {{calculate()}}</p> </div> </body> <script> var myApp = angular.module('myApp', []); myApp.factory("calculateOrderService", function () { //define factory varialble var factory = {}; factory.flatShipping = function (price) { // shipping price value is 10 return price + 10; } factory.customShipping = function (price, shipping) { // shipping price value is 20 return price + shipping; } return factory; }); myApp.controller("myCtrl", function ($scope, calculateOrderService) { $scope.price = 0; $scope.shipping = 0; $scope.total = 0; $scope.shippingtype = "flat"; $scope.calculate = function () { if ($scope.shippingtype == "flat") { $scope.total = calculateOrderService.flatShipping($scope.price); } else { $scope.total = calculateOrderService.customShipping($scope.price, $scope.shipping); } return $scope.total; }; }); </script> </html>

Service

In angularJS, service refers to a singleton object, which stores a set of functions that can be injected into the controller, these functions have logic to help the service handle the job, for example the $http service is used to inject controller to do HTTP operations

To create a service in the module, AngularJS provides the service() method, with this method we define the service and assign the desired methods to it, A service has a constructor function (initialization), using the word new key to create object and put methods and properties in it. However, unlike factory, inside service after definition does not return value, everything is injected into the service through this (the object context itself). A service can be injected into other services, filters, controllers, directives…

Example of initializing data through service:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Example Service</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js"></script> </head> <body ng-app="myApp"> <div ng-controller="myController"> <select ng-model="selectedlistOption" ng-change="alertselected()" ng-options="item as item.name for item in listOption track by item.id"> </select> </div> </body> <script> var app = angular.module('myApp', []); app.service('myService', function () { this.optionDefault = {id: 0, name: "Choose nothing"}; this.addListOption = function (listOption) { listOption.unshift(this.optionDefault); }; }); app.controller('myController', function ($scope, myService) { // $scope.selected = ""; $scope.listOption = [ {id: 1, name: "Option 1"}, {id: 2, name: "Option 2"}, {id: 3, name: "Option 3"}, {id: 4, name: "Option 4"}, ]; myService.addListOption($scope.listOption); $scope.selectedlistOption= $scope.listOption[0]; $scope.alertselected = function(){ console.log($scope.selectedlistOption); } }); </script> </html>

With the above example, I do the work using the service through the injection mechanism, put a default select option in the newly initialized select list and select it as the default selected.

Difference between Service and Factory

Difference Factory Service
Function type (function type) As a function, returns an object or a value Is a constructor function, or initialized via the new . keyword
Use (Use) Used for unconfigured service, often used in complex logical structure Suitable for use in simple logical structures
Properties definition without using this keyword Use this keyword
Friendly Injection mechanism No support Support
Primitives (primitives) Have No
Preferred choice Priority when defining class Prefer when defining quick utilities, or defining ES6 standard functions

Bài viết liên quan:

Expressions in AngularJS
Data binding mechanism in AngularJS
Event handling in angularJS
Filter (filter) in angularJS
Route (routing) in angularJS
Form validation in angularJS
Animation in angularJS
Dependency Injection mechanism in angularJS
Install Visual Studio Code for C/C++ programming on Windows and MacOs
Overview of AngularJS
Integrate AngularJS into the project and write hello world application
Controller in AngularJS

THÊM BÌNH LUẬN Cancel reply

Dịch vụ thiết kế Wesbite

NỘI DUNG MỚI CẬP NHẬT

Step-by-step guide to installing Microsoft SQL Server and connecting to the database for beginners

Reasons Why People Are Increasingly Inexperienced in Life

PHP Data Types

Table (table) in SQL Server

Basic data types in C

Giới thiệu

web888.vn là chuyên trang chia sẻ và cập nhật tin tức công nghệ, chia sẻ kiến thức, kỹ năng. Chúng tôi rất cảm ơn và mong muốn nhận được nhiều phản hồi để có thể phục vụ quý bạn đọc tốt hơn !

Liên hệ quảng cáo: [email protected]

Kết nối với web888

© web888.vn - Tech888 Co .Ltd since 2019

Đăng nhập

Trở thành một phần của cộng đồng của chúng tôi!
Registration complete. Please check your email.
Đăng nhập bằng google
Đăng kýBạn quên mật khẩu?

Create an account

Welcome! Register for an account
The user name or email address is not correct.

Your personal data will be used to support your experience throughout this website, to manage access to your account, and for other purposes described in our privacy policy.

Registration confirmation will be emailed to you.
Log in Lost your password?

Reset password

Recover your password
Password reset email has been sent.
The email could not be sent. Possible reason: your host may have disabled the mail function.
A password will be e-mailed to you.
Log in Register
×