AngularJS quick start

  • 2020-05-24 05:11:48
  • OfStack

How to learn about AngularJS quickly?

Believes that many beginners have or a similar question, in fact, the answer to this question there is no standard, each person's technical background, work experience, and so on are not the same, so learning AngularJS point is different, certainly at the beginning of my previous slightly used knockoutjs, when I first saw the AngularJS Helloworld case, immediately be declarative syntax and attracted by the strong two-way binding characteristics.
In fact, several examples on the homepage of the official website of AngularJS have already well demonstrated some features of AngularJS. In the following, I will explain the attractive things of AngularJS and how ng is used in actual projects step by step from a few examples.

Let's start with the first classic Hello world case, HTML (if you are outside the wall, you can directly access https:// angularjs.org, which runs on the right).


<!doctype html>
<html ng-app>
 <head>
  <script src="http://ngnice.com/lib/angular/1.2.16/angular.js"></script></script>
 </head>
 <body>
  <div>
   <label>Name:</label>
   <input type="text" ng-model="yourName" placeholder="Enter a name here">
   <hr>
   <h1>Hello {{yourName}}!</h1>
  </div>
 </body>
</html>

As anyone who knows how to order HTML at 1 will know, this interface has an input input field, and there is one at the bottom < h1 > The content is Hello {{yourName}}! .

When the user enters content in the input input box, the h1 title below displays "Hello input!" in real time.

It differs from ordinary HTML in the following aspects:

The html tag adds an ng-app attribute, meaning that the entire HTML belongs to the AngularJS control;
An ng-model ="yourName" is added to the input box of input, which indicates that value of input is bidirectional bound to the in-memory variable yourName. Enter "world" in the input box, and the in-memory variable yourName becomes "world", and vice versa.
There is a {{yourName}} inside the h1 tag, which represents the in-memory yourName attribute and the content of h1 node. After yourName is "world", the content of h1 will become "Hello world! ", "{{}}}" is the expression for ng.

Traditional practices:

Add change event on input. When the change event is triggered, get the contents of the input input box, combine the strings, and modify innerHTML of h1 through DOM operation. The premise may be to add id or name attribute to input and h1.
So here's an example.
You should be able to clearly feel the advantages of AngularJS, without having to write 1 line of JS code, you can achieve a perfect function.

The above example just shows a simple two-way binding function. Since AngularJS is an MV* framework, yourName is Model and HTML is View, where is the * (Controller or ViewModel)? Let me modify the above example slightly:


<!doctype html>
  <html ng-app>
  <head>
    <script src="http://ngnice.com/lib/angular/1.2.16/angular.js"></script>
  </head>
  <body>
    <div ng-controller="testCtrl">
      <label>Name:</label>
      <input type="text" ng-model="yourName" placeholder="Enter a name here">
      <button ng-click="clearInputValue()">Clear Input Value</button>
      <hr>
      <h1>Hello {{yourName}}!</h1>

    </div>
    <script>
      function testCtrl($scope) {
        $scope.yourName = "world";
        $scope.clearInputValue = function () {
          $scope.yourName = "";
        }
      }
    </script>
  </body>
</html>

You can see where I modified it:

An ng-controller ="testCtrl" is added to div, indicating that all elements within this DIV belong to the jurisdiction of testCtrl.
At the same time, script adds a function testCtrl, which has a parameter of $scope, and assigns a value of "world" to $scope.yourName. There is also an clearInputValue function, which you can understand as the carrier (or context) of ViewModel, ng Model. All the variables of ng used in the templates are on $scope. The initial assignment to $scope.yourName indicates that the default value of Value in the input input box is "world";
ng-click means that an click event is bound to this Button. Click Button to execute clearInputValue function. This function assigns an empty string to $scope.yourName and empties the value of the input box.

From this example, you can clearly see how AngularJS implements MV*, and you can think about the specific traditional practice. Is ng easier to implement? Have you been attracted by ng so far?

After you look at the above example, maybe some people start to wonder, each controller binds 1 function, the first parameter of this function is $scope, all the data and methods are in the context of $scope, and this function is a global function, what if there are many controller on the interface? You don't have many global functions, do you? (note: this approach to global functions has been removed since version 1.3.x.)

Actually, ng has thought of this step for a long time. ng has its own module loading mechanism and also introduces dependency injection.

I modified the above example again:


<!doctype html>
<html ng-app="app">
 <head>
   <meta charset="utf-8"/>
   <style>
     ul {
       list-style : none;
       clear   : both;
     }
     ul > li {
       list-style : none;
       float    : left;
       margin-left : 15px;
       display   : block;
     }
     .active {
       background : #1f292e;
       color   : #FFFFFF;
     }
     a {
       color : #000066;
     }
     .active > a {
       color : #FFFFFF;
     }
    [ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide{display:none !important;}ng\\:form{display:block;}.ng-animate-start{border-spacing:1px 1px;-ms-zoom:1.0001;}.ng-animate-active{border-spacing:0px 0px;-ms-zoom:1;}
   </style>
 </head>
 <body ng-cloak>
   <div ng-controller="testCtrl">
     <ul>
       <li ng-class="{'active':currentMenu == 'menu1'}"><a href="javascript:;" ng-click="selectMenu('menu1')"> The menu 1</a>
       </li>
       <li ng-class="{'active':currentMenu == 'menu2'}"><a href="javascript:;" ng-click="selectMenu('menu2')"> The menu 2</a>
       </li>
     </ul>
     <br><br>

     <div ng-if="currentMenu == 'menu1'">
        I am a menu 1 What's in there 
     </div>
     <div ng-if="currentMenu == 'menu2'">
        I am a menu 2 What's in there 
     </div>

   </div>
   <script src="http://ngnice.com/lib/angular/1.2.16/angular.js"></script>
   <script>
     angular.module("app", []);
     angular.module("app").controller("testCtrl", ["$scope", function ($scope) {
       $scope.currentMenu = "menu1";
       $scope.selectMenu = function (menu) {
         $scope.currentMenu = menu;
       }
     }]);
   </script>
 </body>
</html>

I gave ng-app a name "app ", and the js code USES angular.module ("app", []); An module named "app" is defined, and an testCtrl is defined using this app module controller method; Define module function is angular static methods on the object, the first parameter name, the second parameter is an array, the array said the other module module reference, in this case we didn't use any other module, so to an empty array, if you don't pass the second parameter, said get name as "app module;"

This example is a menu module that you often encounter in projects. There are two menus on the page. By default, select menu 1.

I used ng-if ="currentMenu == 'menu1'" and ng-if ="currentMenu == 'menu2'" for which content area to display. As the name implies, ng-if means that if the expression is true, it compels and displays the template elements inside ng-if.
For the style of the selected menu, I used ng-class ="{'active':currentMenu == 'menu1'}", which means currentMenu adds class 'active' when menu1, otherwise there is no style at all.

The three examples above show how to turn on ng's web, and how to use ng in a modular way. If you understand them, you have already mastered how to use ng-controller, two-way binding of data, writing templates, and preliminary contact with many built-in instructions (e.g. : ng - app ng - controller ng - model ng - if ng - class ng - click).

To be honest, you already know a lot.

Of course, ng still has many things to discover, such as:

Write SPA (single-page program) in ngRoute module;
There are more rich instructions, learn to encapsulate their own custom instructions;
Filter function of ng (Filter);
ng form validation;
Use the service functions of ng (service, provider and factory);
ng scope tree structure and communication between different controllers through the event publish and subscribe mechanism;
$http and $resource modules interact with API on the server;
Use the animate module to do some animation effects;
Unit tests.
Note: for demonstration purposes, all js css are written on the html page. The actual project should be written in separate files.

The last example

You can make an example of todolist by yourself according to what you have learned above. There are 2 todo on the default interface, 1 todo is completed, and 1 checkbox is unfinished. There is an checkbox in front of each todo to indicate whether it has been completed or not. Instead of looking at the following code, you can try to do 1 on your own. Several directive are needed for this example: < li ng-repeat="todo in todos" > Represents the looping todos list. Within the li tag, you can write the template language to display the contents of each todo, such as {{toodo.text}}.

The code is as follows:


<!DOCTYPE html>
<html ng-app="todoApp">
  <head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
      .done-true {
        text-decoration: line-through;
        color: grey;
      }
    </style>
  </head>
  <body>
    <h2>Todo</h2>
    <div ng-controller="TodoController">
      <span>{{remaining()}} of {{todos.length}} remaining</span>
      [ <a href="" ng-click="archive()">archive</a> ]
      <ul class="unstyled">
        <li ng-repeat="todo in todos">
          <input type="checkbox" ng-model="todo.done">
          <span class="done-{{todo.done}}">{{todo.text}}</span>
        </li>
      </ul>
      <form ng-submit="addTodo()">
        <input type="text" ng-model="todoText" size="30"
            placeholder="add new todo here">
        <input class="btn-primary" type="submit" value="add">
      </form>
    </div>
  <script src="http://ngnice.com/lib/angular/1.2.16/angular.js"></script>
  <script>
    angular.module('todoApp', [])
        .controller('TodoController', ['$scope', function($scope) {
          $scope.todos = [
            {text:'learn angular', done:true},
            {text:'build an angular app', done:false}];

          $scope.addTodo = function() {
            $scope.todos.push({text:$scope.todoText, done:false});
            $scope.todoText = '';
          };

          $scope.remaining = function() {
            var count = 0;
            angular.forEach($scope.todos, function(todo) {
              count += todo.done ? 0 : 1;
            });
            return count;
          };

          $scope.archive = function() {
            var oldTodos = $scope.todos;
            $scope.todos = [];
            angular.forEach(oldTodos, function(todo) {
              if (!todo.done) $scope.todos.push(todo);
            });
          };
        }]);
  </script>
  </body>
</html>

The input boxes and buttons above can be implemented using the code below


<input type="text" ng-model="todoText" size="30"
            placeholder="add new todo here">
        <input class="btn-primary" type="button" value="add" ng-click="addTodo()">

It's used in the official example < form ng-submit="addTodo()" > The implementation is to enable you to enter content and then press the Enter key to submit it.

We also got to know Angular. js1 step by step in the process of doing Worktile, and those Angular. js must tread on 11 pits, there is no doubt that Angular. js is indeed a very excellent front-end MV* framework.

That's all for this article, which I hope will help you as you prepare to use the Angular.js technology.


Related articles: