Table of Contents
Introduction to angularjs
Project body icon
Project setup
index.html
Hello {{yourName}}!
indexController.js
homepage.html (implementation of simple login function)
homeController.js (implementation of simple login Login function)
HttpService.js (network request encapsulation service)
Home Web Front-end JS Tutorial How to build a simple project with AngularJS? Function implementation of angularjs (with complete example)

How to build a simple project with AngularJS? Function implementation of angularjs (with complete example)

Sep 08, 2018 pm 03:24 PM
angularjs

This article mainly talks about the project of getting started with angularjs. Interested students can come in and take a look. There are many codes that you can try.

Introduction to angularjs

AngularJS is a JavaScript framework. AngularJS extends HTML through directives and achieves two-way binding between the page and js data through expressions. The main body adopts the MVC (model, view, controller) mode that developers are very familiar with, and uses the routing (route) mode to implement single page jumps (Ps: the config function of the AngularJS module is used to configure routing rules). AngularJS has many features, the most core of which are: MVC, modularization, automated two-way data binding, semantic tags, dependency injection, etc.
For details, please refer to: PHP Chinese Network AngularJS Development Manual.

PS: If you are a developer using eclipse, you can:
How to build a simple project with AngularJS? Function implementation of angularjs (with complete example)

Project body icon

How to build a simple project with AngularJS? Function implementation of angularjs (with complete example)

Project setup

index.html

<!doctype html><!--html 元素是 AngularJS 应用: ng-app="myApp" 的容器 --><html ng-app="myApp"><head>
     <!--
           所有资源脚本引用需在index页面,如果在子页面引用将失效
           1、一次性全在html加载
           2、用oclazyload插件
           3、自己使用angular的$q 写一个加载文件的服务
      -->
    <script src="js/lib/angular.min.js"></script>
    <script src="js/lib/angular-route.js"></script>
    <script src="js/utils/url.js"></script>
    <script src="js/utils/selfmd5.js"></script>
    <script src="js/utils/toast.js"></script>
    <script type="text/javascript" src="js/lib/jquery.min.js"></script>
    <script src="js/controller/indexController.js"></script>
    <script src="js/controller/homeController.js"></script>
    <script src="js/service/HttpService.js"></script></head><!--body是 HTML 页面中控制器: ng-controller="indexController" 的作用域--><body ng-controller="indexController"><p>
    <label>Name:</label>
    <input type="text" ng-model="yourName" placeholder="Enter a name here">
    <hr>
    <!--数据绑定-->
    <h1 id="Hello-nbsp-yourName">Hello {{yourName}}!</h1>
    <!--p 是 HTML 页面中视图: ng-view 的作用域子页面注入区(PS:本人理解)-->
    <p ng-view>


    </p></p></body></html>
Copy after login

indexController.js

/**
 * Created by Administrator on 2017/12/1.
 */
 //应用程序声明以及将controller、service等放入容器中(PS:类似于SpringMvc的IOC容器)var myApp = angular.module(&#39;myApp&#39;,["ngRoute",&#39;homeController&#39;,&#39;httpService&#39;]);//控制器声明myApp.controller(&#39;indexController&#39;, [&#39;$scope&#39;,function($scope) {
    //数据绑定
    $scope.yourName= &#39;Hola!&#39;;    //ng-view监听
    $scope.$on("$viewContentLoaded",function(){
        console.log("ng-view content loaded!");
    });    $scope.$on("$routeChangeStart",function(event,next,current){
        //event.preventDefault(); //cancel url change
        console.log("route change start!");
    });
}]);//模块的 config 函数用于配置路由规则myApp.config(function($routeProvider, $locationProvider) {
    $routeProvider
        .when(&#39;/home&#39;, {
            templateUrl: &#39;content/homepage.html&#39;,            //如果路由对页面指明了controller,页面无需使用ng-controller="homeController"声明,否则将会              //出现homeController多次调用
            controller: &#39;homeController&#39;
        })
        .otherwise({
            redirectTo: &#39;/home&#39;
        });
});
Copy after login

homepage.html (implementation of simple login function)

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title>SingleCase</title></head><body ><!--数据绑定-->
        <input ng-model="user.account"/>
      <!--  <input ng-model="user.password"/>-->
        <input ng-model="user.pwd"/>
        <!--事件绑定--><input type="button" ng-click="login()"><!--列表遍历--><ul ng-repeat="menu in menus">
    <li  ng-click="menu_2Show(menu.lid)" >{{menu.name}}
        <ul ng-repeat="menu_list  in menu.menu_list"  style="display: none"   id="menu_2{{menu.lid}}">
            <li  ng-click="menu_2Click(menu_list.name)"> {{menu_list.name}}</li>
        </ul>
    </li></ul></body></html>
Copy after login

homeController.js (implementation of simple login Login function)

/**
 * Created by Administrator on 2017/12/1.
 */angular.module("homeController",["ngRoute"])
 <!--注入service等工具-->
 .controller("homeController",function($scope,$route,httpService,$location){
       <!--声明modle进行数据绑定-->        $scope.user={account:&#39;&#39;,password:&#39;&#39;,pwd:&#39;&#39;};
          <!--对密码进行MD5加密-->        $scope.user.password = hex_md5($scope.user.pwd);
        <!--登陆方法-->        $scope.login=function(){
         <!--调用封装的post请求-->
            httpService.postReq(  $scope.user,&#39;/loginbusiness/login&#39;,&#39;用户登陆!&#39;).then(function(data){
                if(data.code>0){                //controller中进行路由跳转
                    $location.path("/home");
                }else{                 //Android效果toast
                    alerToast(data.code+&#39;:&#39;+data.msg,2000);
                }
            });
        };        $scope.role={role:0};        $scope.menus=null;
        httpService.postReq(  $scope.role,&#39;&#39;,&#39;用户登陆!&#39;).then(function(data){
            $scope.menus=data.data;
        });        $scope.menu_2Click=function(name){
            alerToast(name,2000);
        }        $scope.menu_2Show=function(lid){
            $(&#39;#menu_2&#39;+lid).show();
        }
    });
Copy after login

HttpService.js (network request encapsulation service)

/**
 * Created by Administrator on 2017/9/28.
 */angular.module("httpService",[])//请求头设置   PS:可写 拦截器 全局$http注入loading效果

    .config(["$httpProvider", function ($httpProvider) {
        //更改 Content-Type
        $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";        $httpProvider.defaults.headers.post["Accept"] = "*/*";        $httpProvider.defaults.transformRequest = function (data) {
            //把JSON数据转换成字符串形式
            if (data !== undefined) {                return $.param(data);
            }            return data;
        };
    }])
    .service(&#39;httpService&#39;, function( $http,$q) {
    //生成deferred异步对象
        var deferred=$q.defer();
        this.postReq = function(reqdata,api,msg) {
            console.log(msg+":start!");            $http({
                method: "POST",
                url: lh_business_url+api,
                headers: { &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded;charset=utf-8&#39; },
                data:reqdata
            }).success(function(data, status) {
                console.log(data);                //执行到这里时,改变deferred状态为执行成功,返回data为从后台取到的数据,可以继续执行then,done
                deferred.resolve( data);
            }).
                error(function(data, status) {
                    alert(&#39;连接服务器出错!&#39;);                    //执行到这里时,改变deferred状态为执行失败,返回data为报错,可以继续执行fail
                    // deferred.reject(&#39;连接服务器出错!&#39;);
                });
            console.log(msg+":end!");            //起到保护作用,不允许函数外部改变函数内的deferred状态
            return deferred.promise;
        };
        this.getReq = function(data,api,msg) {
            console.log(msg+":start!");            $http.get(lh_business_url+api, {
                params:data
            }).success(function (data) {
                console.log(data);                // 如果连接成功,延时返回给调用者
                deferred.resolve(data);
            }) .error(function () {
                alert(&#39;连接服务器出错!&#39;);                // deferred.reject(&#39;连接服务器出错!&#39;);
            });
            console.log(msg+":end!");            return deferred.promise;
        };
    });
Copy after login

This article ends here (if you want to see more, go to the PHP Chinese websiteAngularJS User Manual 中文), if you have any questions, you can leave a message below.

The above is the detailed content of How to build a simple project with AngularJS? Function implementation of angularjs (with complete example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The latest 5 angularjs tutorials in 2022, from entry to mastery The latest 5 angularjs tutorials in 2022, from entry to mastery Jun 15, 2017 pm 05:50 PM

Javascript is a very unique language. It is unique in terms of the organization of the code, the programming paradigm of the code, and the object-oriented theory. The issue of whether Javascript is an object-oriented language that has been debated for a long time has obviously been There is an answer. However, even though Javascript has been dominant for twenty years, if you want to understand popular frameworks such as jQuery, Angularjs, and even React, just watch the "Black Horse Cloud Classroom JavaScript Advanced Framework Design Video Tutorial".

Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Jun 27, 2023 pm 07:37 PM

In today's information age, websites have become an important tool for people to obtain information and communicate. A responsive website can adapt to various devices and provide users with a high-quality experience, which has become a hot spot in modern website development. This article will introduce how to use PHP and AngularJS to build a responsive website to provide a high-quality user experience. Introduction to PHP PHP is an open source server-side programming language ideal for web development. PHP has many advantages, such as easy to learn, cross-platform, rich tool library, development efficiency

Build web applications using PHP and AngularJS Build web applications using PHP and AngularJS May 27, 2023 pm 08:10 PM

With the continuous development of the Internet, Web applications have become an important part of enterprise information construction and a necessary means of modernization work. In order to make web applications easy to develop, maintain and expand, developers need to choose a technical framework and programming language that suits their development needs. PHP and AngularJS are two very popular web development technologies. They are server-side and client-side solutions respectively. Their combined use can greatly improve the development efficiency and user experience of web applications. Advantages of PHPPHP

Use PHP and AngularJS to develop an online file management platform to facilitate file management Use PHP and AngularJS to develop an online file management platform to facilitate file management Jun 27, 2023 pm 01:34 PM

With the popularity of the Internet, more and more people are using the network to transfer and share files. However, due to various reasons, using traditional methods such as FTP for file management cannot meet the needs of modern users. Therefore, establishing an easy-to-use, efficient, and secure online file management platform has become a trend. The online file management platform introduced in this article is based on PHP and AngularJS. It can easily perform file upload, download, edit, delete and other operations, and provides a series of powerful functions, such as file sharing, search,

How to use PHP and AngularJS for front-end development How to use PHP and AngularJS for front-end development May 11, 2023 pm 05:18 PM

With the popularity and development of the Internet, front-end development has become more and more important. As front-end developers, we need to understand and master various development tools and technologies. Among them, PHP and AngularJS are two very useful and popular tools. In this article, we will explain how to use these two tools for front-end development. 1. Introduction to PHP PHP is a popular open source server-side scripting language. It is suitable for web development and can run on web servers and various operating systems. The advantages of PHP are simplicity, speed and convenience

How to use AngularJS in PHP programming? How to use AngularJS in PHP programming? Jun 12, 2023 am 09:40 AM

With the popularity of web applications, the front-end framework AngularJS has become increasingly popular. AngularJS is a JavaScript framework developed by Google that helps you build web applications with dynamic web application capabilities. On the other hand, for backend programming, PHP is a very popular programming language. If you are using PHP for server-side programming, then using PHP with AngularJS will bring more dynamic effects to your website.

Build a single-page web application using Flask and AngularJS Build a single-page web application using Flask and AngularJS Jun 17, 2023 am 08:49 AM

With the rapid development of Web technology, Single Page Web Application (SinglePage Application, SPA) has become an increasingly popular Web application model. Compared with traditional multi-page web applications, the biggest advantage of SPA is that the user experience is smoother, and the computing pressure on the server is also greatly reduced. In this article, we will introduce how to build a simple SPA using Flask and AngularJS. Flask is a lightweight Py

Introduction to the basics of AngularJS Introduction to the basics of AngularJS Apr 21, 2018 am 10:37 AM

The content of this article is about the basic introduction to AngularJS. It has certain reference value. Now I share it with you. Friends in need can refer to it.

See all articles