Part 20 Create custom service in AngularJS

Whenever the case changes from lower to upper, a single space character should be inserted. This means the string "AngularVideoTutorial" should be converted to"Angular Video Tutorial".

Let us first see, how to achieve this without using a custom service.

HtmlPage1.html :

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/angular.js"></script>
    <script src="Scripts/Script.js"></script>
    <link href="Styles.css" rel="stylesheet" />
</head>
<body ng-app="myModule">
    <div ng-controller="myController">
        <table>
            <tr>
                <td>Your String</td>
                <td><input type="text" ng-model="input" /> </td>
            </tr>
            <tr>
                <td>Result</td>
                <td><input type="text" ng-model="output" /></td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="button" ng-click="transformString(input)"
                           value="Process String" />
                </td>
            </tr>
        </table>
    </div>
</body>
</html>

Script.js : Notice, all the logic to insert a space when the case changes is in the controller. There are 2 problems with this
1. The controller is getting complex
2. This logic cannot be reused in another controller. If you have to use this logic in another controller, we will have to duplicate this same code with in that controller.

When we use our own custom service to encapsulate this logic, both of these problems go away. The custom service can be injected into any controller where you need this logic.

var app = angular
        .module("myModule", [])
        .controller("myController", function ($scope) {
            $scope.transformString = function (input) {
                if (!input)
                    return input;

                var output = "";

                for (var i = 0; i < input.length; i++) {
                    if (i > 0 && input[i] == input[i].toUpperCase()) {
                        output = output + " ";
                    }

                    output = output + input[i];
                }

                $scope.output = output;
            };
        });

Now let‘s create a custom service. Here are the steps
1. Add a JavaScript file to the Scripts folder in the project. Name it stringService.js.
2. Copy and paste the following code. Notice we are using the factory method to create and register the service with Angular.

app.factory(‘stringService‘, function () {
    return {
        processString: function (input) {
            if (!input)
                return input;

            var output = "";

            for (var i = 0; i < input.length; i++) {
                if (i > 0 && input[i] == input[i].toUpperCase()) {
                    output = output + " ";
                }

                output = output + input[i];
            }

            return output;
        }
    };
});

3. Copy and paste the following code in Script.js. Notice that we have injected stringService into the controller function.

var app = angular
        .module("myModule", [])
        .controller("myController", function ($scope, stringService) {
            $scope.transformString = function (input) {
                $scope.output = stringService.processString(input);
            };
        });

4. On HtmlPage1.html, only one change is required and that is to reference the stringService.js script file

<script src="Scripts/stringService.js"></script>

时间: 2024-08-06 11:57:55

Part 20 Create custom service in AngularJS的相关文章

[转]How to Create Custom Filters in AngularJs

本文转自:http://www.codeproject.com/Tips/829025/How-to-Create-Custom-Filters-in-AngularJs Introduction Filter in Angular JS is a way that will help you to represent your data in View in a certain format. There are many inbuilt filters provided by Angular

Part 17 Consuming ASP NET Web Service in AngularJS using $http

Here is what we want to do1. Create an ASP.NET Web service. This web service retrieves the data from SQL Server database table, returns it in JSON formt.2. Call the web service using AngularJS and display employee data on the web page Step 1 : Create

配置ssh框架启动tomcat服务器报异常Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

在Spring中配置jdbc时,引用的是dbcp.jar包,在db.properties配置文件中,使用了之前的properties配置文件的用户名username(MySql用户名) 然后在启动服务器报了如下几个异常: 1.org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [a

Unable to create requested service org.hibernate.cache.spi.RegionFactory

hibernate 4.3.11+struts2.3.28.1+spring 4.2.5,在搭框架的时候,报的这个错误: Unable to create requested service org.hibernate.cache.spi.RegionFactory 折腾了半天,发现是少包了,这提示根本看不出来吗,额 少了ehcache的包,这个包在hibernate里面 ehcache-core-2.4.3.jar hibernate-ehcache-4.3.11.Final.jar slf4

Create Custom Modification Form In VS 2012-Part2

1.SPWorkflowModification ContextData is XMLSerialized as String. 2.Get SPWorkflowModification ContextData in modification page protected void GetContexData()        {            SPWeb currentWeb = SPContext.Current.Web;            string strWorkflowI

Create Custom Modification Form In VS 2012-Part1

Step1.Add EventHandlingScope Activity Under OnWorkflowActivated Step2.Add SequenceActivity In EventHandlingScope Activity Step3.Add EnableWorkflowModification Activity a.Bind [ContextData] to a new field b.Set [Colorrelation Token] as "Modification&q

java中如何创建自定义异常Create Custom Exception

9.创建自定义异常 Create Custom Exception  (视频下载) (全部书籍) 马克-to-win:我们可以创建自己的异常:checked或unchecked异常都可以, 规则如前面我们所介绍,反正如果是checked异常,则必须或者throws,或者catch.到底哪个好,各路架构师大神的意见是50对50.见我本章后面的附录.sun公司开始说,checked异常可以使你的系统异常语义表达很清楚.但很多人经过一段时间的实践后,马上表示了异议.checked异常是java独有的,

Mysql——安装server错误:cannot create windows service

在安装到最后一步,点击”execute“按钮时,出现错误cannot create windows service for mysql.error:0 解决方法: 在桌面上找到“MyComputer“,右键选择“Manage”,然后选择”Service and Applications“,然后选择”services“,找到”MySQL“服务: 右键”Stop“此服务后.以管理员身份打开cmd:   输入命令:sc delete mysql 此命令是删除”MySQL“服务.刷新”services“

Part 18 $http service in AngularJS

In Angular there are several built in services. $http service is one of them. In this video, we will discuss another built in service, $log. It is also possible to create our own custom services in Angular. At this point several questions come to our