Angular JS - 将ng-click $索引值传递给控制器​​函数,然后返回到另一个视图

问题描述:

我将ng-click $ index值传递给我的控制器,然后将它的值用于ng-repeat中的数据但得到一个错误提示“ReferenceError:myChoice没有定义”

我的看法(months.html)有一个所有月份的列表,当它被选中时,它将值传递给控制器​​。

<ion-list ng-repeat="time in times.months" ng-click="getMonthId($index)" style=""> 
    <ion-item style="" href="#/dmtimes">{{ time.monthId }} - {{ time.MonthName }</ion-item> 
</ion-list> 

视图输出是示出了:

1 - Jan 
2 - Feb 
3 - Mar 
etc 

我的控制器具有以下提取代码:

.controller('dailyMeetingTimesCtrl', function($scope, MeetingNames, $ionicLoading, $firebase, $firebaseArray) { 

    $scope.getMonthId = function (monthId) { 
    alert("you selected: " + monthId); // this works fine. 
    $scope.myChoice = monthId; // ReferenceError: myChoice is not defined 

    console.log(myChoice); 
    } 
}) 

以我第二视图(displayMeetingTimes.html)我想显示的会议详情,时间等等。的代码如下:

<ion-view title="Daily Meeting Times"> 
    <ion-content ng-controller="dailyMeetingTimesCtrl" class="has-header" overflow-scroll="true" padding="true"> 
    <ion-list> 

     <ion-item ng-repeat="time in times.months(myChoice).days" class="item-text-wrap"> 
     <span>{{myChoice}}</span> 
     Meeting Name: {{ time.meetingName }}<br /> 
     Star Time: {{ time.startTime }}<br /> 
     Finish Time: {{ time.finishTime }}<br /> 
     </ion-item>   
    </ion-list> 

    </ion-content> 
</ion-view> 

当我跑的应用中,“myChoice”不通过传递到第二视图因此错误值“的ReferenceError:myChoice没有定义”

请告知我哪里错了?谢谢。

+0

应该是'的console.log($ scope.myChoice);',不是吗? –

+0

谢谢console.log($ scope.myChoice);现在有用。 – GreenDome

当你想通过$index使用ng-repeat,你需要指定它。所以,你的HTML应该像如下:

<ion-list ng-repeat="time in times.months track by $index" ng-click="getMonthId($index)" style=""> 
    <ion-item style="" href="#/dmtimes">{{ time.monthId }} - {{ time.MonthName } 
    </ion-item> 
</ion-list> 

其次,为什么你越来越ReferenceError: myChoice is not defined的原因是因为你从来没有初始化一个名为myChoice变量。但是,您确实有一个名为$scope.myChoice的变量。
因此,你应该做到以下几点显示变量在控制台:

console.log($scope.myChoice); 
+0

谢谢......我已经按照建议对HTMl进行了更改,但在第二个HTML文件中,我该如何读取myChoice值?即不起作用... – GreenDome

+1

''不要在视图中放置'$ scope'。当你访问'$ scope'变量时,你不会把'$ scope'放在html中。 –

+0

我已经试过了,我得到一个错误:“TypeError:v12.months不是一个函数”,这对我没有多大意义。你知道为什么吗?谢谢。 – GreenDome