SoFunction
Updated on 2025-03-10

Detailed explanation of AngularJS syntax (continued)

src and href attributes

In Angularjs, src should be written as ng-src, and href should be written as ng-href For example:

Copy the codeThe code is as follows:

<img ng-src="/images/cats/{{favoriteCat}}">
<a ng-href="/shop/category={{number}}">Some text</a>

expression

Simple mathematical operations, comparison operations, Boolean operations, bit operations, reference arrays, and object symbols can be performed in templates. Although we can do a lot of things with expressions, the expression is executed using a custom interpreter (part of Angular), rather than using Javascript eval() function, so it has great limitations.
Although the expressions here are stricter than Javascript in many ways, they have better fault tolerance to undefined and null. If an error is encountered, the template is simply showing nothing without throwing a NullPointerException error. For example:

Copy the codeThe code is as follows:

<div ng-controller='SomeController'>
<div>{{computer() /10 }}</div> //Although it is legal, it puts business logic into the template, and this approach should be avoided
</div>

Distinguish between UI and controller responsibilities

The controller is bound to a specific DOM fragment, which is what they need to manage. There are two main methods to associate the controller to the DOM node. One is declared through the ng-controller in the template, and the second is to bind it to a dynamically loaded DOM template fragment through routing. This template is called a view. We can create nested controllers, they can share data model and functions by inheriting the number structure. The real nesting occurs on the $scope object. Through the internal original inheritance mechanism, the $scope of the parent controller object will be passed to the internal nested $scope (all properties, including functions). For example:

Copy the codeThe code is as follows:

<div ng-controller="ParentController">
    <div ng-controller="ChildController">...</div>
</div>

Expose model data using $scope

You can display the creation of $scope attribute, such as $=5. You can also indirectly create data models through the template itself.

Pass expression. For example

Copy the codeThe code is as follows:

<button ng-click='count=3'>Set count to three</button>

Using ng-model on form items

Similar to the expression, the model parameters specified on ng-model also work within the outer controller. The only difference is that this creates a two-way binding relationship between the form item and the specified model.

Monitor changes in data models using watch

The function signature of $watch is: $watch(watchFn,watchAction, deepWatch)
watchFn is a string with an Angular expression or function that returns the current value of the monitored data model. watchAction is a function or expression called when watchFn changes. Its function signature is:
function(newValue,oldValue,scope) deepWatch If set to true, this optional boolean parameter will command Angular to check whether each property of the monitored object has changed. If you monitor a simple value to monitor elements in the array, or all attributes on the object, instead of values, you can use this parameter. Note that Angular needs to traverse arrays or objects. If the set is larger, then the operation will be more complicated.

The $watch function returns a function. When you do not need to receive change notifications, you can use this returned function to log out of the monitor.
If we need to monitor a property and then log out of monitoring, we can use the following code: var dereg = $scope.$watch('',callbackOnChange());
... dereg();

The example code is as follows:

Copy the codeThe code is as follows:

<html ng-app>
<head>
    <title>Your Shopping Cart</title>
    <script type="text/javascript">
        function CartController($scope) {
            $ = {};
            $ = [
                {title:'Paint pots',quantity:8,price:3.95},
                {title:'Polka dots',quantity:17,price:12.95},
                {title:'Pebbles',quantity:5,price:6.95}
            ];
            $ = function() {
                var total = 0;
                for (var i=0,len=$;i<len;i++) {
                    total = total + $[i].price * $[i].quantity;
                }
                return total;
            }
            $ = function() {
                return $() - $;
            }
            function calculateDiscount(newValue,oldValue,scope) {
                $ = newValue > 100 ? 10 : 0;
}//The watchAction function here
$scope.$watch($,calculateDiscount);//The watch function here
        }
    </script>
</head>
<body>
    <div ng-controller="CartController">
        <div ng-repeat='item in items'>
            <span>{{}}</span>
            <input ng-model=''>
            <span>{{ | currency}}</span>
            <span>{{ * | currency}}</span>
        </div>
        <div>Total: {{totalCart()| currency }}</div>
        <div>Discount: {{ | currency}}</div>
        <div>SubTotal: {{subtotal() | currency}}</div>
    </div>
    <script type="text/javascript" src=""></script>
</body>
</html>

The above watch has performance problems. The calculatedTotals function was executed 6 times, three of which were because the loop was broken. Each time the loop was looped, the data was re-rendered.
Below is the modified code

Copy the codeThe code is as follows:

<html ng-app>
<head>
    <title>Your Shopping Cart</title>
    <script type="text/javascript">
        function CartController($scope) {
            $ = {};
            $ = [
                {title:'Paint pots',quantity:8,price:3.95},
                {title:'Polka dots',quantity:17,price:12.95},
                {title:'Pebbles',quantity:5,price:6.95}
            ];
            var totalCart = function() {
                var total = 0;
                for (var i=0,len=$;i<len;i++) {
                    total = total + $[i].price * $[i].quantity;
                }
                $ = total;
                $ = total > 100 ? 10 :0;
                $ = total - $;
            }
$scope.$watch('items',totalCart,true);//Only watch the changes of items
        }
    </script>
</head>
<body>
    <div ng-controller="CartController">
        <div ng-repeat='item in items'>
            <span>{{}}</span>
            <input ng-model=''>
            <span>{{ | currency}}</span>
            <span>{{ * | currency}}</span>
        </div>
        <div>Total: {{| currency }}</div>
        <div>Discount: {{ | currency}}</div>
        <div>SubTotal: {{ | currency}}</div>
    </div>
    <script type="text/javascript" src=""></script>
</body>
</html>

For large itms arrays, if only the bill attribute is recalculated each time the page is displayed in Angular, the performance will be much better. We can achieve this by creating a $watch function with watchFn.

Copy the codeThe code is as follows:

$scope.$watch(
    var totalCart = function() {
                var total = 0;
                for (var i=0,len=$;i<len;i++) {
                    total = total + $[i].price * $[i].quantity;
                }
                $ = total;
                $ = total > 100 ? 10 :0;
                $ = total - $;
            });

Monitor multiple things

If you want to monitor multiple properties or objects and execute a function when any of them changes, you have two basic options:

Monitor the values ​​after connecting these properties

Put them in an array or object, and then pass a value to the deepWAtch parameter

Explain separately:
In the first case, if there is a things object in your scope, it has two properties a and b, and when both properties change, you need to execute the callMe() function, you can monitor these two properties at the same time $scope.$watch(' + ',callMe(...));
When the list is very long, you need to write a function to return the value after the connection.

In the second case, you need to monitor all properties of the things object, you can do this:

Copy the codeThe code is as follows:

$scope.$watch('things',callMe(...),true);

Organize dependencies using module

provider(name,Object OR constructor()) Description: A configurable service, creating logic is relatively complex. If you pass an Object as a parameter, then the Object object must have a function named $get, which needs to return the service name. Otherwise, angularjs will think that when you pass a constructor, calling the constructor will return the service instance object.
factory(name,$get Function()) Description: A non-configurable service, the creation logic is relatively complicated. You need to specify a function, and when this function is called, the service instance will be returned. It can be regarded as the form of provider(name,{$get:$getFunction()}).
service(name,constructor()) is a non-configurable service, creating logic is relatively simple. Similar to the constructor parameter of the provider function above, Angular calls it to create a service instance.

Example of using module factory

Copy the codeThe code is as follows:

<html ng-app='ShoppingModule'>
<head>
<title>Your Shopping Cart</title>
<script type="text/javascript" src=""></script>
<script type="text/javascript">
    var ShoppingModule = ('ShoppingModule',[]);
    ('Items',function() {
        var  items = {};
        = function() {
            return [
                {title:'Paint pots',description:'Pots full of Paint',price:3.95},
                {title:'Paint pots',description:'Pots full of Paint',price:3.95},
                {title:'Paint pots',description:'Pots full of Paint',price:3.95}
            ];
        };
        return items;
    });
    function ShoppingController($scope,Items) {
        $ = ();
    }
</script>
</head>
<body ng-controller='ShoppingController'>
<h1>Shop!!</h1>
<table>
    <tr ng-repeat='item in items'>
        <td>{{}}</td>
        <td>{{}}</td>
        <td>{{ | currency}}</td>
    </tr>
</table>
</body>
</html>

Introducing third-party modules

In most applications, create a single module for all code and put all the dependencies into this module, which will work well. However, if you plan to use services or instructions provided by third-party packages, they usually come with their own modules, and you need to define dependency care in the application module to reference them. For example:
var appMod = ('app',['Snazzy','Super']);

Examples about filter

Copy the codeThe code is as follows:

<html ng-app='ShoppingModule'>
<head>
<title>Your Shopping Cart</title>
<script type="text/javascript" src=""></script>
<script type="text/javascript">
    var ShoppingModule = ('ShoppingModule',[]);
    ('titleCase',function() {
        var titleCaseFilter = function(input) {
            var words = (' ');
            for(var i=0;i<;i++) {
                words[i] = words[0].charAt(0).toUpperCase() + words[i].slice(1);
            }
            return (' ');
        };
        return titleCaseFilter;
    });
    function ShoppingController($scope) {
        $ = 'this is a test case';
    }
</script>
</head>
<body ng-controller='ShoppingController'>
<h1>{{pageHeading | titleCase}}</h1>
</body>
</html>