AngluarJS - 作用域

先看一段代码:

<html ng-app = "app">
    <head>
        <meta charset="utf-8">
        <title></title>
        <script type="text/javascript" src="../angular-1.6.9/angular.js"></script>
    </head>
    <body ng-controller="initController as init">
        <div>
            price: <input type="number" ng-model="price"/><br>
            amount: <input type="number" ng-model="amount"/><br>
            total: {{init.total()}}
        </div>
        <script type="text/javascript">
            function initController($scope) {
                $scope.price = 8.0;
                $scope.amount = 10;
                this.total = function() {
                    return $scope.price * $scope.amount;
                }
            }
            var app = angular.module("app", []);
            app.controller("initController", initController);
        </script>
    </body>
</html>

这样是可以的。

<html ng-app = "app">
    <head>
        <meta charset="utf-8">
        <title></title>
        <script type="text/javascript" src="../angular-1.6.9/angular.js"></script>
    </head>
    <body>
        <div  ng-controller="initController as init">
            price: <input type="number" ng-model="price"/><br>
            amount: <input type="number" ng-model="amount"/><br>
            total: {{init.total()}}
        </div>
        <script type="text/javascript">
            function initController($scope) {
                $scope.price = 8.0;
                $scope.amount = 10;
                $scope.total = function() {
                    return $scope.price * $scope.amount;
                }
            }
            var app = angular.module("app", []);
            app.controller("initController", initController);
        </script>
    </body>
</html>

这样则不行:

this.total = function() { return $scope.price * $scope.amount;}的意思是将total()方法挂在当前作用控制器的作用域上。但是
$scope.total = function() {return $scope.price * $scope.amount;}的意思却是将total()方法挂在$scope上。显然$scope作用域要大于initController作用域的,你是不可以在一个相对较小的作用域上去访问一个超出你作用域范围上的对象(但是变量却可以访问)的。这些细节的挖掘是十分耗费时间的,尤其是出入门的菜鸟。理解了细节,才是对概念的真正把握。

posted on 2018-09-06 17:11  TrustNature  阅读(10)  评论(0)    收藏  举报