ANGULARJS USES the ng bind directive to implement an example of one way binding

  • 2020-03-30 04:31:06
  • OfStack

After a brief introduction to the AngularJS framework, an example is presented to demonstrate the use of {{}} interpolation and ng-bind instruction.

Unlike jquery, which is just a library to enhance and simplify front-end development, angularjs is a complete web front-end framework, so the learning curve is much higher.

Angularjs gives me a feeling similar to Java's Spring framework, where other components are glued together in a central container position. Many of its built-in components can already be used for general scenarios, and special scenarios can be extended according to the framework.

Below is the most basic content from start:


<!DOCTYPE html>
<html ng-app>
<head>
    <meta charset="utf-8">
    <title>ng-bind directive</title>
</head>
<body ng-controller="HelloController">
<div>
    <p> Output string literals directly </p>
    Hello {{"World"}}
    <hr>
</div> <div>
    <p> Use placeholders to output variables </p>
    Hello {{greeting}}
    <hr>
</div> <div>
    <p> use ng-bind Instruction output variable </p>
    Hello <span ng-bind="greeting"></span>
    <hr>
</div> <script src="../lib/angularjs/1.2.26/angular.min.js"></script>
<script>
    function HelloController($scope) {
        $scope.greeting = "World";
    }
</script>
</body>
</html>

Ng-app declares an angularjs module and is limited to declaring HTML tags.

Ng-controller is a controller that declares an angularjs controller in a module. There can be more than one controller, but the context is isolated.

{{}} is angularjs's interpolation syntax, similar to JSP's EL expression ${}. The first output because "World" is a literal, the program will output directly; The second output because the greeting is a variable defined in the controller, will also output the value of the variable, again, World; The third output takes advantage of angularjs's built-in ng-bind property directive, and the end result is equivalent to {{}}}, but note that the instruction = is followed by a string, so don't make a mistake.

The HelloController in js corresponds to the instruction above the body. The input parameter $scope is a service provided by the framework, which represents the context of the current controller. There are other similar services. The method body is one line long and defines a variable on $scope, which is the variable referenced in the HTML code.

This article is very simple, the code can be copied to run. Note that angular.min.js is the latest version of the 1.2 branch, and the same code cannot be run with version 1.3.0 for unknown reasons. Maybe 1.3.0 is not the final Release.


Related articles: