SoFunction
Updated on 2025-03-10

Example of using NG-BIND instruction to implement one-way binding in ANGULARJS

After briefly introducing the AngularJS framework, this article uses an example to demonstrate the use of {{}} interpolation method and ng-bind instruction.

Unlike jquery, which is just a class library that strengthens and simplifies front-end development, angularjs is a complete web front-end framework, so the learning curve is much higher.

angularjs gives me the feeling that it is similar to Java's Spring framework, which glues other components in the center container position. Many of its built-in components can already meet general scenarios, and we can expand special scenarios according to the framework idea.

Let’s start with the most basic content:

Copy the codeThe code is as follows:

<!DOCTYPE html>
<html ng-app>
<head>
    <meta charset="utf-8">
    <title>ng-bind directive</title>
</head>
<body ng-controller="HelloController">
<div>
<p>Directly output string literals</p>
    Hello {{"World"}}
    <hr>
</div>

<div>
<p>Use placeholders to output variables</p>
    Hello {{greeting}}
    <hr>
</div>

<div>
<p>Use ng-bind instruction to output variables</p>
    Hello <span ng-bind="greeting"></span>
    <hr>
</div>

<script src="../lib/angularjs/1.2.26/"></script>
<script>
    function HelloController($scope) {
        $ = "World";
    }
</script>
</body>
</html>

ng-app declares an angularjs module and is limited to the scope of declaring html tags.

ng-controller declares an angularjs controller in the module. The controller can have multiple controllers, but the context is isolated, and the scope of the controller should be narrowed as much as possible.

{{}} is the interpolation syntax of angularjs, similar to the EL expression ${} of JSP. The first output is because "World" is a literal value, and the program will output directly; the second output is because greeting is a variable defined in the controller, so the corresponding value of the variable will also be output, which is also World; the third output uses the built-in ng-bind attribute instruction of angularjs, and the final result is equivalent to {{}}, but please note that the instruction = is followed by a string, do not write it incorrectly.

The HelloController in js corresponds to the instructions on body. The entry parameter $scope is a service provided by the framework, representing the context of the current controller, and there are other similar services. The framework will be automatically injected and we will slowly understand it later. The method body has only one line, and it defines a variable on $scope, which is the variable referenced in the html code.

This article is very simple, and you can run the code after copying it. Note that the latest version of the 1.2 branch, the same code cannot run with the 1.3.0 version. The reason is unknown. It may be that 1.3.0 is not the final Release version.