Get started with node. JS Development-Using ANGULARJS built-in services

Source: Internet
Author: User

In the previous article, "Angularjs Simple Example " demonstrates a very simple use of angular's small demo, the article has been too long, the original to introduce some of the content had to separate the beginning. The content is how to use the angular service.

We're still using the example in the "Angularjs Simple Example " to retrofit. New example to get the admin menu from the node.js+express constructed server. In order to achieve this, several parts need to be modified:

    • Server provides adminmenu download function, need to modify app.js, handle routing
    • Modify the controller X-controller implemented by the angular, using the $http service to download from the Web server Adminmenu
    • Modify the HTML template to trigger the download action
Modify App.js

First of all, the encoding format of the App.js file is changed to UTF8, because I write in the code directly in Chinese. The code is as follows:

var express = require (' Express '), var path = require (' path '), var favicon = require (' Serve-favicon '); var logger = require (' m Organ '), var cookieparser = require (' Cookie-parser '), var bodyparser = require (' Body-parser '), var routes = require ('./ Routes/index '); var users = require ('./routes/users '); var app = Express ();//View engine Setupapp.set (' views ', Path.join ( __dirname, ' views '); App.set (' View engine ', ' jade ');//Uncomment after placing your Favicon In/public//app.use (Favicon ( Path.join (__dirname, ' public ', ' Favicon.ico ')); App.use (Logger (' dev ')); App.use (Bodyparser.json ()); App.use ( Bodyparser.urlencoded ({extended:false})); App.use (Cookieparser ()); App.use (Express.static (Path.join, '    Public ')); App.use ('/', routes); App.use ('/users ', users); App.get ('/adminmenu ', function (req, res, next) {var menus = [          {text: "System Management", Enabled:true, submenus:[{text: "User Management", Enabled:true, Action: "/admin/adduser"}, {text:"Role Management", Enabled:true, Action: "/role"}, {text: "Rights Management", enabled : True, Action: "/access"}]}, {text: "Content Management", Enabled:false, submenus          : [{text: "Live stream Monitor", Enabled:true, Action: "/stream-monitor"}, { Text: "Appointment Management", enabled:true, Action: "/book-mgr"}]}, {text: "Push Management"         , Enabled:true, submenus:[{text: "Push list", Enabled:true, Action: "/push-list"        }, {text: "New Push", Enabled:false, Action: "/add-push"}]  }      ];  Res.status. Send (menus);  });//catch 404 and forward to the error handlerapp.use (function (req, res, next) {var err = new error (' Not Found ');  Err.status = 404; Next (err);}); /error handlers//development error handler//would print Stacktraceif (APP.get (' env ') = = = ' Development ') {App.use (function (err, req, res, next) {Res.status (Err.status | | 500);  Res.render (' error ', {message:err.message, error:err}); });} Production error handler//no stacktraces leaked to Userapp.use (function (err, req, res, next) {Res.status (err.status ||  500); Res.render (' error ', {message:err.message, error: {}}); Module.exports = app;

Starting with the line "App.get ('/adminmenu '), I added code that responds to/adminmenu. The Enabled property for some menu items is also set so that the menu obtained from the server differs from the local menu in the angular simple example.

Trigger Download

I modified the admin.html document and used the ng-init directive to execute the Init method within the scope. Within the Init method, use the $http service to download the Management menu.

The new HTML file was renamed by me to Admin2.html and was still placed in the public directory. Only two lines of code were changed compared to admin.html,admin2.html:

  <body>    <div class="x-view-full" ng-controller="x-controller" ng-init="init()">    ......    <script src="/javascripts/admin2.js"></script>  </body>

The NG-INIT directive allows us to execute a JS expression within the current scope.

Download the admin menu using the $http service

I modified the admin.js, with the same name as Admin2.js, placed in the Public/javascripts directory. Admin2.js content is as follows:

angular.module(‘x-admin‘, []).controller(‘x-controller‘, [‘$scope‘, ‘$http‘, function ($scope, $http) {  $scope.currentUser="ZhangSan";  $scope.content = ‘/welcome.html‘;  $scope.menus = [];  $scope.init = function(){    $http.get("/adminMenu")         .success(function(data, status, headers, config){           console.log("got menus");           $scope.menus = data;         })         .error(function(data, status, headers, config){           console.log("got menus failed. status - " + status);         });  };  $scope.setContent = function(action){    console.log(action);    $scope.content=action;  };}]);

I defined the Init method for the scope to be called by the ng-init instruction within the HTML document. Within the Init method, the http service was used to download the Adminmenu.

The usage of the http service does not explain much, just look at the document.

I gave the success method a callback, and when the download succeeds, modify the menus property of the scope to assign a direct value to the menus attribute to the JSON array downloaded from/adminmenu. From node. js backend to angular front end, JSON to JSON, no conversion, acid cool!

$http the parameters of the Get method are URIs, such as the usage in the example, you can omit the domain name section. You can also use the full URL, such as Http://localhost:3000/adminMenu, and the effect is the same.

The browser's XMLHttpRequest (XHR) object is used internally $http service.

OK, finally, you access "http://localhost:3000/admin2.html" in the browser, the effect may be this:

View-angular-admin2.png

Another way of writing

In fact, this simple example, can be used without ng-init instructions, it is simpler, admin2.html and admin.html only a little difference: the HTML reference admin.js modified to admin2.js. Then, modify the Admin2.js, directly within the Controller's constructor to start the download. The new code is as follows:

angular.module(‘x-admin‘, []).controller(‘x-controller‘, [‘$scope‘, ‘$http‘, function ($scope, $http) {  $scope.currentUser="ZhangSan";  $scope.content = ‘/welcome.html‘;  $scope.menus = [];  $http.get("http://localhost:3000/adminMenu")         .success(function(data, status, headers, config){           console.log("got menus");           $scope.menus = data;         })         .error(function(data, status, headers, config){           console.log("got menus failed. status - " + status);         });  $scope.setContent = function(action){    console.log(action);    $scope.content=action;  };}]);
More Angular services

Angular provides a lot of built-in services, in order to use in the controller, in the controller constructor parameters directly write the name of the service, angular automatically for us to complete the dependency injection.

angular.module(‘x-admin‘, []).controller(‘x-controller‘, [‘$scope‘, ‘$http‘, function ($scope, $http)

The above code, the X-controller constructor depends on the < Span class= "Mrow" id= "mathjax-span-152" > s c o p e and HTTP, if you want to use other services, such as $window, can be changed to the following:

angular.module(‘x-admin‘, []).controller(‘x-controller‘, [‘$scope‘, ‘$http‘, ‘$window‘, function ($scope, $http, $window)

This is too cumbersome to write more characters, I still like this:

controller(‘x-controller‘, function ($scope, $http, $interval) {

Well, that's it, more services look here: Https://code.angularjs.org/1.3.7/docs/api/ng/service.

Other articles:

    • node. JS Development Primer--angular Simple Example
    • Introduction to node. JS Development-Using ANGULARJS
    • Getting Started with node. JS Development-Using the Jade template engine
    • node. JS Development Starter--express Routing and middleware
    • node. JS Development Primer--express Installation and use
    • node. JS Development Primer--http File Server
    • node. JS Development Primer--helloworld Re-analysis
    • Introduction to node. JS Development--Environment building and HelloWorld

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Get started with node. JS Development-Using ANGULARJS built-in services

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.