【问题标题】:Binding to primitive value on controller绑定到控制器上的原始值
【发布时间】:2016-07-22 04:32:31
【问题描述】:

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

当我使用 chrome 角度扩展检查范围时,我看到 ctrl.loading 是 true。

这是因为布尔值是 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请求wq返回后设置值。

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

但效果是一样的。

【问题讨论】:

  • 不应该是$scope.ctrl.loading = false 而不是loading = false 吗?

标签: javascript angularjs javascript-databinding


【解决方案1】:

您错误地绑定了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>

另外,控制器中的返回块也没用。

编辑

现在,我明白你的问题了。这是我第一次看到这种从控制器返回的功能。经过半个小时的研究,我发现你不能期望一个原始类型在 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>

【讨论】:

  • 看我的小提琴:link。我可以通过这种方式绑定到控制器上的数据,这就是控制器中的 return 语句的用途。
  • 哦,你想让我看看return这个东西吗?
  • 不确定你的意思。我只是说 return 语句有一个用途,并且在我的代码中,如果我将加载的初始值更改为 true,它将显示未加载,而不是加载。初始绑定有效,只是更新无效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
相关资源
最近更新 更多