使用AngularJs

时间:2016-11-09 09:41:01

标签: javascript jquery angularjs

使用angularJs时,调用返回字符串并在标签中显示该字符串的函数的最佳方法是什么?

我有三个下拉菜单,当我在所有菜单中选择值时,我想显示一个标签。 标签的内容是在一个函数中计算的,所以在那一刻(当所有3个下拉都选择了一些值时)我需要调用将返回标签值的函数。

我隐藏/显示标签逻辑的所有内容都是这样的:

<div class="col-md-2" 
        ng-show="newTestSessionCtrl.formData.sessionTime && newTestSessionCtrl.formData.timeZone && newTestSessionCtrl.formData.sessionCloseInterval">
    <lable>Your local time</lable>
    <div ng-value="convertSelectedTimeZoneToClients()"></div>
</div>

这是convertSelectedTimeZoneToClients()函数代码:

convertSelectedTimeZoneToClients() {
    let timeZoneInfo = {
        usersTimeZone: this.$rootScope.mtz.tz.guess(),
        utcOffset: this.formData.timeZone.offset,
        selectedDateTime: this.toJSONLocal(this.formData.sessionDate) + " " + this.formData.sessionTime 
    };

    let utcTime  = this.$rootScope.mtz.utc(timeZoneInfo.selectedDateTime).utcOffset(timeZoneInfo.utcOffset).format("YYYY-MM-DD HH:mm");
    let localTime = this.$rootScope.mtz.utc(utcTime).toDate();
    localTime = this.$rootScope.mtz(localTime).format("YYYY-MM-DD HH:mm");
    return localTime;
}

因此,当选择值时,我会显示标签:您当地时间 在下面我想显示来自convertSelectedTimeZoneToClients()的结果,该结果基本上是字符串&#39; YYYY-MM-DD HH:mm &#39;格式。

我可以在html上预先形成这样的东西,或者我必须转移到控制器吗?实现这一目标的最佳或最简单的方法是什么?

我尝试过ng-value,但我想我做错了。什么都没有显示,但我也没有在控制台中出现任何错误。

3 个答案:

答案 0 :(得分:0)

试试这个:

<div ng-bind="convertSelectedTimeZoneToClients()"></div>

答案 1 :(得分:0)

在您的函数中,您可以检查是否选择了下拉列表,然后计算并返回结果

$scope.getData = function () {
        if ($scope.ValueOfFirstDropDown != undefined && $scope.ValueOfSecondDropDown != undefined && $scope.ValueOfThirdDropDown != undefined) {
            //calculate result
            return result;

        }

    }

并在你的HTML中

<label>{{getData()}}</label>

答案 2 :(得分:0)

您应该在更改所选值时调用此函数

<select ng-change="convertSelectedTimeZoneToClients();"></select>


<div class="col-md-2" 
        ng-show="newTestSessionCtrl.formData.sessionTime && newTestSessionCtrl.formData.timeZone && newTestSessionCtrl.formData.sessionCloseInterval">
    <lable>Your local time</lable>
    <div ng-bind="clientDateTimeZone"></div>
</div>

并反映$scope.clientDateTimeZone = yourreturnedvalue

无需返回任何内容

   $scope.convertSelectedTimeZoneToClients = function()  {
    let timeZoneInfo = {
      usersTimeZone: this.$rootScope.mtz.tz.guess(),
      utcOffset: this.formData.timeZone.offset,
      selectedDateTime: this.toJSONLocal(this.formData.sessionDate) + " " + this.formData.sessionTime
    };

    let utcTime = this.$rootScope.mtz.utc(timeZoneInfo.selectedDateTime).utcOffset(timeZoneInfo.utcOffset).format("YYYY-MM-DD HH:mm");
    let localTime = this.$rootScope.mtz.utc(utcTime).toDate();
    localTime = this.$rootScope.mtz(localTime).format("YYYY-MM-DD HH:mm");
    //set It here
    $scope.clientDateTimeZone = localTime
      //return localTime;
  }