如何在指令中使用trackby $ index的$ index

时间:2016-06-09 10:20:59

标签: javascript jquery angularjs

这是我的HTML

 <tr ng-show="option == 'Yearly' || option == 'Date'">
            <td>
                <label>From:</label>
            </td>
            <td>
                <input type="text" ng-model="fromdate" id="from" date-picker date-type="from" month-directive />
                {{fromdate}}
            </td>

            <td>
                <label>To:</label>
            </td>
            <td>
                <input id="todate" type="text" ng-model="todate" date-picker date-type="to" month-directive />
                {{todate}}
            </td>

        </tr>

.....

<div ng-repeat=" month in months track by $index" ng-hide="fromdate == '' || todate =='' ||option != 'Yearly'">
        {{$index}}
        <input class="toBeChecked" type="checkbox" checker-directive>
        <label ng-bind="month"></label>
    </div>

这是我的指示

scope.$watch('todate', function (newValue, oldValue) {
            toDate = new Date(newValue);
            toDate = moment(newValue, 'YYYY-MM-DD');
            var range = moment.range(fromDate, toDate);

            range.by('months', function (moment) {

               var monthArray = moment.toArray('months');
                for (var i = 0; i <= scope.months.length; i++)
                {
                    var status = false;
                        if (i == monthArray[1]) {
                            status = true;
                        }

                    if(status)
                    {
                        $('.toBeChecked').prop('disabled', false);
                    }
                    else
                    {
                        $('.toBeChecked').prop('disabled', true);
                    }
                }

            });
        });

    }

我想知道如何在我的指令中获取$ index的值。如果状态为true,如何禁用特定复选框?有人可以建议我如何执行此操作。提前感谢。

2 个答案:

答案 0 :(得分:0)

存储对应于每个月份对象的布尔变量,并使用该布尔变量来跟踪复选框点击状态。

使用此代码: -

html.ts

<div ng-repeat=" month in months track by month.id" ng-hide="fromdate == '' || todate =='' ||option != 'Yearly'">
        {{$index}}
        <input class="toBeChecked" type="checkbox" ng-model="month.selected" checker-directive ng-change="$ctrl.updateFunction()">
        <label ng-bind="month"></label>
</div>

示例月份对象

{
   id : "unique_id",
   selected: "booleanValue",
   day: "day_data",
   month: "month_data"
}

controller.js可以包含

function updateFunction () {
    console.log("inside update function");
}

答案 1 :(得分:0)

尝试使用ng-change

 <td>
       <input type="text" ng-change="changed(this)" ng-model="fromdate" id="from" date-picker date-type="from" month-directive />
                {{fromdate}}
            </td>

和同样的   

<input id="todate" type="text" ng-model="todate" ng-change="changed(this)" date-picker date-type="to" month-directive />
            {{todate}}
        </td>

并在您的控制器中

$scope.changed(self){
    console.log(self); //contians the value
}