繁体   English   中英

绑定到控制器上的原始值

[英]Binding to primitive value on controller

我试图绑定到我的控制器范围内的布尔变量,以指示是否应显示加载动画。 但是,以下代码不起作用。 $timeout内的函数运行,但视图未更新。

当我使用chrome角度扩展检查范围时,我看到ctrl.loadingtrue

这是因为布尔值是javascript中的值类型,而不是引用类型?

我的猜测是视图字面上与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>

上面的代码只是一个例子,我真的会在返回get请求后设置值。

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

但效果是一样的。

您错误地绑定了loading变量。 您需要将该变量loading注册到$scopethis变量。 请参阅以下工作示例:

 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> 

此外,控制器中的返回块是没有用的。

编辑

现在,我理解你的问题。 这是我第一次看到从控制器返回的这个功能。 经过半个小时的研究,我发现你不能指望在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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM