Home  >  Article  >  Web Front-end  >  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)

寻∝梦
寻∝梦Original
2018-09-08 15:24:113864browse

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>Hello {{yourName}}!</h1>
    <!--p 是 HTML 页面中视图: ng-view 的作用域子页面注入区(PS:本人理解)-->
    <p ng-view>


    </p></p></body></html>

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;
        });
});

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>

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();
        }
    });

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;
        };
    });

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:
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