SoFunction
Updated on 2025-04-04

AngularJS Quick Start

How to quickly understand AngularJS?

I believe many beginners have had or similar questions. In fact, there is no standard answer to this question. Everyone has different technical background, work experience, etc., so the entry point of learning AngularJS is definitely different. I used knockoutjs before. When I first saw the Helloworld case of AngularJS, I was immediately attracted by the declarative syntax and powerful two-way binding features.
In fact, several examples from the homepage of AngularJS's official website have shown some of the features of AngularJS well. Below I will explain the attractive things of AngularJS and how to use ng in actual projects from a few examples.

First of all, start with the first classic Hello world case, as follows HTML (if you are outside the wall, you can directly access it., there will be a running effect on the right).

<!doctype html>
<html ng-app>
 <head>
  <script src="/lib/angular/1.2.16/"></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>

Anyone who knows a little HTML knows that this interface has an input input box, and there is a title of <h1> below, which is Hello {{yourName}}!.

The effect is: when the user enters content in the input input box, the h1 title below displays "Hello input content!" in real time!

The differences from ordinary HTML are as follows:

An ng-app attribute is added to the html tag, which means that the entire HTML is controlled by AngularJS;
An ng-model="yourName" is added to the input input box, which means that the input value is bidirectionally bound to the variable yourName in memory. If you enter "world" in the input box, the yourName variable in memory becomes "world", and vice versa;
There is a {{yourName}} inside the h1 tag, which means that yourName property in memory and the content of the h1 node implements two-way binding. After yourName is "world", the content of h1 will become "Hello world!", and "{{}}" is an expression of ng.

Traditional practice:

Add a change event on the input. When the change event is triggered, get the content of the input input box, then combine the string, and modify the innerHTML of h1 through DOM operations. The premise may be to add an id or name attribute to input and h1.
By this example.
Everyone should be able to clearly feel the advantages of AngularJS. It can achieve a perfect function without writing a line of JS code.

The above example only shows a simple two-way binding function. Since AngularJS is an MV* framework, yourName mentioned above is Model and HTML is View, so where did * (Controller or ViewModel) go? I'll modify the above example a little:

<!doctype html>
  <html ng-app>
  <head>
    <script src="/lib/angular/1.2.16/"></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) {
        $ = "world";
        $ = function () {
          $ = "";
        }
      }
    </script>
  </body>
</html>

You can see where I modified:

Add an ng-controller="testCtrl" to the div, indicating that all elements inside this DIV are under the jurisdiction of testCtrl;
At the same time, script adds a function testCtrl. This function has a $scope parameter, and a "world" value is assigned to $. There is also a clearInputValue function. This $scope can be understood as ViewModel, the carrier (or context) of ng Model. All ng variables used in the template are on $scope. Initialization and assignment to $ indicates that the value of the input input box is "world" by default;
There is an extra Button on the interface, and there is an ng-click="clearInputValue()" on the button. ng-click means that a click event is bound to this Button. Click Button to execute the clearInputValue function. This function assigns an empty string to $ and clears the value of the input box.

From this example, you can clearly see how AngularJS implements MV*. You can think about the specific traditional practices in your mind. Is the implementation of ng simpler? Are you attracted by ng so far? ? ?

After you have looked at the above example, some people may start to ask, each controller is bound to a function, the first parameter of this function is $scope, all data and methods are in the context of $scope, and this function is a global function, what if there are many controllers on the interface? There won't be many global functions, right? (Note: This method of global function has been cancelled after version 1.)

Haha, in fact, ng has long thought of this step. ng has its own set of module loading mechanisms and has also introduced dependency injection.

I modified the above example again:

&lt;!doctype html&gt;
&lt;html ng-app="app"&gt;
 &lt;head&gt;
   &lt;meta charset="utf-8"/&gt;
   &lt;style&gt;
     ul {
       list-style : none;
       clear   : both;
     }
     ul &gt; li {
       list-style : none;
       float    : left;
       margin-left : 15px;
       display   : block;
     }
     .active {
       background : #1f292e;
       color   : #FFFFFF;
     }
     a {
       color : #000066;
     }
     .active &gt; 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;}
   &lt;/style&gt;
 &lt;/head&gt;
 &lt;body ng-cloak&gt;
   &lt;div ng-controller="testCtrl"&gt;
     &lt;ul&gt;
       &lt;li ng-class="{'active':currentMenu == 'menu1'}"&gt;&lt;a href="javascript:;" ng-click="selectMenu('menu1')"&gt;menu1&lt;/a&gt;
       &lt;/li&gt;
       &lt;li ng-class="{'active':currentMenu == 'menu2'}"&gt;&lt;a href="javascript:;" ng-click="selectMenu('menu2')"&gt;menu2&lt;/a&gt;
       &lt;/li&gt;
     &lt;/ul&gt;
     &lt;br&gt;&lt;br&gt;

     &lt;div ng-if="currentMenu == 'menu1'"&gt;
       我是menu1Contents inside
     &lt;/div&gt;
     &lt;div ng-if="currentMenu == 'menu2'"&gt;
       我是menu2Contents inside
     &lt;/div&gt;

   &lt;/div&gt;
   &lt;script src="/lib/angular/1.2.16/"&gt;&lt;/script&gt;
   &lt;script&gt;
     ("app", []);
     ("app").controller("testCtrl", ["$scope", function ($scope) {
       $ = "menu1";
       $ = function (menu) {
         $ = menu;
       }
     }]);
   &lt;/script&gt;
 &lt;/body&gt;
&lt;/html&gt;

I assigned a name called "app". At the same time, the js code uses ("app", []); to define a module named "app", and at the same time, use the controller method of this app module to define a testCtrl; the module function is a static method on the angular object, the first parameter passes the name, and the second parameter is an array, which represents other modules referenced by this module. In this example, we did not use any other modules, so an empty array is passed in. If the second parameter is not passed, it means that the module named "app" is obtained;

This example is a menu module that you often encounter in projects. There are 2 menus on the page. Menu 1 is selected by default. When selecting which menu is selected, the content area below will display the content of the selected menu. At the same time, the menu style needs to be modified to the selected state;

Regarding which content area to display I used ng-if="currentMenu == 'menu1'" and ng-if="currentMenu == 'menu2'", as the name implies, ng-if means if the expression is true and the template element inside ng-if is displayed, if false, no content is displayed;
As for the style of the menu, I used ng-class="{'active':currentMenu == 'menu1'}", which means that when currentMenu is menu1, there will be no style.

The above three examples show how to enable an ng web and how to use ng modularly. If you understand it, it means that you have mastered how to use ng-controller, two-way binding of data, write templates, and have initially been exposed to many built-in instructions (such as: ng-app, ng-controller, ng-model, ng-if, ng-class, ng-click).

To be honest, you already know a lot.

Of course, there are still many things waiting for you to slowly discover, such as:

Write SPA (single-page program) using ngRoute module;
There are more rich instructions, learn to encapsulate custom instructions yourself;
ng's filter function (Filter);
ng's form verification function;
Use ng's service functions (service, provider and factory);
ng scope tree structure and communicates between different controllers through event publishing subscription mechanism;
The $http and $resource modules interact with the server API;
Use the animate module to do some animation effects;
Unit tests.
Note: For the convenience of displaying the above example, all js css are written in the html page, and the actual project should be written separately in separate files.

The final example

You can make a todolist example by yourself based on the knowledge learned above. There are 2 todos on the default interface, one is completed and the other is not completed. There is a checkbox in front of each todo to indicate whether it has been completed. There is an input box and an add button below. Click Add to enter the content and there will be an additional todo on the list. You can try it yourself without looking at the following code first. Several directives that need to be used in this example: <li ng-repeat="todo in todos"> represent a loop todos list. You can write a template language inside the li tag to display the content of each todo, such as {{}}.

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 {{}} remaining</span>
      [ <a href="" ng-click="archive()">archive</a> ]
      <ul class="unstyled">
        <li ng-repeat="todo in todos">
          <input type="checkbox" ng-model="">
          <span class="done-{{}}">{{}}</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="/lib/angular/1.2.16/"></script>
  <script>
    ('todoApp', [])
        .controller('TodoController', ['$scope', function($scope) {
          $ = [
            {text:'learn angular', done:true},
            {text:'build an angular app', done:false}];

          $ = function() {
            $({text:$, done:false});
            $ = '';
          };

          $ = function() {
            var count = 0;
            ($, function(todo) {
              count +=  ? 0 : 1;
            });
            return count;
          };

          $ = function() {
            var oldTodos = $;
            $ = [];
            (oldTodos, function(todo) {
              if (!) $(todo);
            });
          };
        }]);
  </script>
  </body>
</html>

The above input box and button can be implemented using the following code.

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

The reason why the official example uses <form ng-submit="addTodo()"> is to implement it to enable the input content to be submitted directly and press Enter.

We also learned step by step in the process of working on Worktile, and we have stepped on all the pitfalls that must be stepped on. There is no doubt that it is indeed a very excellent front-end MV* framework.

The above is the entire content of this article. I hope this article can help you who are preparing to use technology.