Angular ng-show 取决于函数

Angular ng-show depending on function

也许这只是一个基本的误解,但我有一个关于 Angular 和 ng-show 的小问题。

我有一个包含三个输入字段的简单表单。我想显示带有信息文本的 div,但前提是所有三个输入字段都已设置。

我的控制器(使用 controllerAs-Syntax,别名是 'myControllerCtrl')看起来像这样:

var vm = this;

vm.annualConsumption = null;
vm.calorificVal = null;
vm.zNumber = null;
vm.checkIfAllValuesAreSet = checkIfAllValuesAreSet;


function checkIfAllValuesAreSet() {
    return vm.annualConsumption && vm.calorificVal && vm.zNumber;
}

所以我放了一个

ng-show="myControllerCtrl.checkIfAllValuesAreSet()"

在我的 div 中。但如果我设置所有输入字段,它不会显示 div!如果我将函数中的条件直接放入 ng-show like

ng-show="vm.annualConsumption && vm.calorificVal && vm.zNumber"

有效。所以我的问题是:为什么我不能将该函数用作 ng-show 的表达式?

您可以将函数用作表达式,但要确保函数 returns 是 boolean。 试试这个:

function checkIfAllValuesAreSet() {
if( vm.annualConsumption !=null && vm.calorificVal !=null && vm.zNumber !=null){
return true;
}

您没有使用 $scope。将函数附加到控制器的范围,你就可以开始了:

$scope.checkIfAllValuesAreSet = function() {
   return vm.annualConsumption && vm.calorificVal && vm.zNumber;
}

因此在您的 HTML 中您将能够:

ng-show="checkIfAllValuesAreSet()"

请记住,$scope 是 angularjs 的一个非常重要的概念。试图避免使用它是一个 糟糕的 想法。 您可以阅读有关 $scope here.

的文档

您的 ng-show="myControllerCtrl.checkIfAllValuesAreSet()" 只会在 controller/template 加载时获得 运行 一次。因此,如果您更改表单上的任何内容,则不会再次触发该功能。

您可以简单地将您的 ng-show 更改为:

ng-show="vm.annualConsumption && vm.calorificVal && vm.zNumber"

如果其中任何一项发生变化,将立即更新。