2016-07-22 5 views
1

내 컨트롤러 범위의 부울 변수에 바인딩하여로드 애니메이션을 표시할지 여부를 나타냅니다. 그러나 다음 코드는 작동하지 않습니다. $timeout 내부의 기능이 실행되지만보기가 업데이트되지 않습니다.컨트롤러의 프리미티브 값에 바인딩

크롬 각도 확장을 사용하여 스코프를 검사 할 때 ctrl.loadingtrue입니다.

참조 유형과 달리 자바 스크립트에서 값 유형이 부울 때문에 발생합니까?

제 생각에 뷰는 글자 그대로 true에 바인딩되며 변경 될 부울 값의 위치가 아닙니다.

뷰가 변수에 바인딩되는 것이 아니라 변수에 바인딩되도록하려면 어떻게해야합니까?

컨트롤러 :

function TestController($scope,$timeout){ 
    "use strict"; 

    var loading=true; 

    $timeout(function(){ 
     loading=false; 
    }, 1000); 

    return { 
     loading:loading 
    } 

} 

템플릿 :

<div> 
    <h1 ng-show="ctrl.loading">Loading</h1> 
    <h1 ng-hide="ctrl.loading">Not Loading</h1> 
</div> 

abovecode가 GET 요청이 반환 wqas 후 정말 내가 값을 설정합니다, 그냥 예입니다.

$http.get().then(function() { 
    loading=false; 
}, function() { 
    loading=false; 
}) 

그러나 효과는 같습니다.

+3

그것이 있어야하지 않나요'$ scope.ctrl.loading = false' 대신'loading = false'를 사용합니까? – Titus

답변

3

loading 변수를 잘못 바인딩하고 있습니다. 변수 loading$scope 또는 this 변수에 등록해야합니다. 아래의 실시 예의 참조 :

var app = angular.module("sa", []); 
 

 
app.controller("TestController", TestController); 
 

 
function TestController($scope, $timeout) { 
 
    "use strict"; 
 
    var vm = this; 
 

 
    vm.loading = true; 
 

 
    $timeout(function() { 
 
    vm.loading = false; 
 
    }, 2000); 
 

 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 

 
<div ng-app="sa" ng-controller="TestController as ctrl"> 
 
    <h1 ng-show="ctrl.loading">Loading</h1> 
 
    <h1 ng-hide="ctrl.loading">Not Loading</h1> 
 
</div>

는 또한 제어기에 리턴 블록이 소용된다.

편집

지금, 나는 당신의 질문을 이해합니다. 컨트롤러에서 돌아 오는이 기능을 처음 보았습니다. 연구 30 시간 후, 나는 원시 타입이 Javascript에서 참조로 전달 될 것이라고 기대할 수 없다는 것을 알아 냈다. 어떤 개체를 사용해야합니다.

요지 얻을 수있는 범위를 상속 문제를 참조하십시오 : https://github.com/angular/angular.js/wiki/Understanding-Scopes

는이 문제를 해결하기를, 당신은 다음과 같은 코드를 변경할 수 있습니다 :

var app = angular.module("sa", []); 
 

 
app.controller("TestController", TestController); 
 

 
function TestController($scope, $timeout) { 
 
    "use strict"; 
 
    var myData = {}; 
 

 
    myData.loading = true; 
 

 
    $timeout(function() { 
 
    myData.loading = false; 
 
    }, 2000); 
 

 
    return { 
 
    myData: myData 
 
    }; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="sa" ng-controller="TestController as ctrl"> 
 
    <h1 ng-show="ctrl.myData.loading">Loading</h1> 
 
    <h1 ng-hide="ctrl.myData.loading">Not Loading</h1> 
 
</div>

+0

내 피들보기 : [link] (http://jsfiddle.net/40k8j2L6/). 그런 식으로 컨트롤러의 데이터에 바인딩 할 수 있으며 컨트롤러의 return 문을위한 것입니다. –

+0

오. 내가 돌아 오는 것을 보길 원해? –

+0

그 의미가 확실하지 않습니다.나는 return 문에 사용법이 있다는 것을 말하고 있는데, 코드에서로드의 초기 값을 true로 변경하면 로딩 대신로드되지 않는 것으로 표시됩니다. 초기 바인딩은 업데이트가 아니라 작동합니다. –