簡體   English   中英

JavaScript Angular 1.5.x控制器

[英]JavaScript Angular 1.5.x Controller

在學習Angular 1.5時,我對標記的用法感到非常困惑。

即,我不明白為什么需要一個“全局”對象來包含控制器內的變量。

JS Bin: http : //jsbin.com/puyayocomi/11/edit?html, js, output

問題是為什么我們不能調用直接在控制器內創建的變量,而不是使用全局對象(在本例中稱為“命名空間”)來保存所有控制器變量?

index.html:

<!DOCTYPE html>
<html ng-app="todoApp">
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    </head>
    <body>
        <h2> Angular Controllers </h2>

        <!-- Why not : ng-controller="todoCtrl" -->
        <div ng-controller="todoCtrl as namespace">
        <!--                                    -->    
            <ul class="unstyled">
                <!-- Why not : ng-repeat="todo in todos" -->
                <li ng-repeat="todo in namespace.todos">
                <!--                                     -->
                    <label class="checkbox">
                        <input type="checkbox" ng-model="todo.done">
                        <span class="done-{{todo.done}}">{{todo.text}}. </span>
                    </label>
                </li>
            </ul>
        </div>
    </body>
</html>

JavaScript:

console.log( 'Hello Script!' );

angular.module( 'todoApp',[] ).controller( 'todoCtrl',function()
{
    var namespace = this;

    namespace.todos =
    [
    { text:'one', done:true },
    { text:'two', done:false }
    ];

    /* 
    <!-- Why not : -->

    var todos =
    [
    { text:'one', done:true },
    { text:'two', done:false }
    ];
    */
})

基本上,它取決於功能范圍在JavaScript中的工作方式:

 function Controller() { // local variable var foo = 1; // instance property this.bar = 2; } // imagine Angular creates an instance of your controller like this: var instance = new Controller(); console.log('foo', instance.foo) // undefined console.log('bar', instance.bar) // 2 

簡而言之:局部變量不能從函數外部訪問,而綁定this屬性可以。

我發現了一種更好的方法,將$ scope變量傳遞給函數控制器,它將為您提供html查找變量的名稱空間。

JS斌在這里

HTML

    <div ng-controller="todoCtrl">
        <ul class="unstyled">
            <li ng-repeat="todo in todos">
                <label class="checkbox">
                    <input type="checkbox" ng-model="todo.done">
                    <span class="done-{{todo.done}}">{{todo.text}}</span>
                </label>
            </li>
        </ul>
    </div>

JavaScript:

angular.module( 'todoApp',[] ).controller( 'todoCtrl',function( $scope )
{    
    $scope.todos =
    [
      { text:'one', done:true },
      { text:'two', done:false }
    ];
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM