如何让$ index命名变量以角度工作?

时间:2016-02-02 01:06:00

标签: javascript jquery angularjs datepicker

我的html上有一个div,编码如下:

<div ng-repeat="loss in Model.plDetails track by $index">
<div class="col-sm-2">
    <div class="input-group">
        <input type="text" class="form-control" datepicker-popup="MM/dd/yyyy" ng-model="loss.Date" id="loss-date{{$index+1}}"
               datepicker-pattern="((0[13578]|1[02])[-/]31[-/](18|19|20)[0-9]{2})|((01|0[3-9]|1[1-2])[-/](29|30)[-/](18|19|20)[0-9]{2})|((0[1-9]|1[0-2])[-/](0[1-9]|1[0-9]|2[0-8])[-/](18|19|20)[0-9]{2})|((02)[-/]29[-/](((18|19|20)(04|08|[2468][048]|[13579][26]))|2000))"
               is-open="datePicker{{$index+1}}.opened" max="maxDate" max-date="maxDate" date-format placeholder="MM/DD/YYYY"/>
        <span class="input-group-btn">
            <button type="button" class="btn btn-default" ng-click="open($event,'datePicker{{$index+1}}')"><i class="icon icon-calendar"></i></button>
        </span>
    </div>
</div>
<div class="col-sm-2">
    <input type="number" ng-model="loss.amount" placeholder="$ Amount" />
</div>
<div class="col-sm-2">
    <select ng-model="loss.type" placeholder="Loss Type">
        <option value="0"></option>
        <option value="2">Test</option>
    </select>
</div>
<div class="col-sm-2">
    Add Line
</div>
</div>

&#34;打开&#34;函数在我的javascript中编码为:

$scope.open = function ($event, targetDatePicker) {
     $event.preventDefault();
     $event.stopPropagation();
     $scope[targetDatePicker].opened = !$scope[targetDatePicker].opened;
}

问题是,当我尝试运行此代码时,我首先得到一个错误&#34;语法错误:令牌&#39; {&#39;表达式[datePicker {{$ index + 1}}的第11列是一个意外的标记。已打开]从[{{$ index + 1}}开始。已打开]。&#34;这是在定义了is-open的代码行上。

如果我将is-open更改为datePicker1.opened,它的工作原理会超出错误(但从长远来看,我的代码不会工作,因为我需要最后一个数字是可变的)但是还有另一个问题。单击日历图标以触发ng-click事件时,出现错误&#34;无法读取属性&#39;打开&#39;未定义&#34;因为&#34; targetDatePicker&#34;而被抛出被解释为不存在的datePicker {{$ index + 1}}。

必须有一种方法来评估这些值,以便它们以datePicker1,datePicker2等形式出现......

更新:我还尝试了This StackOverflow Answer处的代码。我尝试将代码设置为:

            $scope.datePicker = {};
            $scope.open = function ($event, idx) {
            $event.preventDefault();
            $event.stopPropagation();
            $scope.datePicker['idx' + idx].opened = !$scope.datePicker['idx' + idx].opened;
        };

将HTML设为<input type="text" class="form-control ng-pristine ng-valid ng-isolate-scope ng-empty ng-valid-date ng-touched" datepicker-popup="MM/dd/yyyy" ng-model="loss.Date" id="loss-date1" datepicker-pattern="((0[13578]|1[02])[-/]31[-/](18|19|20)[0-9]{2})|((01|0[3-9]|1[1-2])[-/](29|30)[-/](18|19|20)[0-9]{2})|((0[1-9]|1[0-2])[-/](0[1-9]|1[0-9]|2[0-8])[-/](18|19|20)[0-9]{2})|((02)[-/]29[-/](((18|19|20)(04|08|[2468][048]|[13579][26]))|2000))" is-open="datePicker['idx'+$index].opened" max="maxDate" max-date="maxDate" date-format="" placeholder="MM/DD/YYYY">但我仍然收到Cannot read property 'opened' of undefined错误。

2 个答案:

答案 0 :(得分:1)

第一个错误,您在}属性中缺少is-open,这会使角度不解析它而只是文本,所以

is-open="datePicker{{$index+1}.opened"

将其更改为

is-open="datePicker{{$index+1}}.opened"

现在,在你的ng-click中,你不需要双{{}},angularjs不需要评估它来将字符串传递给函数,你只需要这样的东西

ng-click="open($event,'datePicker'+($index+1))"

这将是神奇的。

我不知道你使用的日期选择器是如何工作的,我只是指出我在你的代码中看到的错误。希望它有所帮助

<强> EDITED
我写了一个说明性的例子,只是为了让你看到语法,也许你可以找到一段可以帮助你解决问题的代码。

<!DOCTYPE html>
<html>
<head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <title>.:[Angularjs test]:.</title>
      <script type="text/javascript" src="jquery-1.10.2.js"></script>
      <script type="text/javascript" src="angular.js"></script>
      <script type="text/javascript">
        (function () {
            'use strict';

            angular.module('kstr', []);
            angular
                .module('kstr')
                .controller('KstrController', KstrController);

            function KstrController(){
                var self = this;
                self.myList = ["kstro", "jhon", "jane"];
                self.datePicker = {};

                self.printit = function(index){
                    console.log(self.datePicker[index]);
                    self.datePicker[index].opened = !self.datePicker[index].opened;
                }
            }
        })();
      </script>
</head>
<body data-ng-app="kstr">
    <div class="row" data-ng-controller="KstrController as kstr">
        <div data-ng-repeat="myItem in kstr.myList track by $index">
            <p>My item "{{myItem}}" with "datePicker{{$index+1}}"</p>
            <div data-ng-init="kstr.datePicker[$index+1]={opened:false}">
                <pre>var datePicker[{{$index+1}}].opened = {{kstr.datePicker[$index+1].opened}}</pre>
            </div>
            <div>
                <button type="button" data-ng-click="kstr.printit($index+1)">Change it</button>
            </div>
        </div>
    </div>
</body>
</html>

答案 1 :(得分:0)

所以我在这里解决了这个问题。我最终将打开的东西移动到我的对象,细节必然会被绑定。这是通过open函数传递的,现在似乎都可以正常工作。

        $scope.Model.plDetails = [{ date: "", amount: "", opened: false, type: 1 }];
        $scope.open= function ($event, loss) {
            $event.preventDefault();
            $event.stopPropagation();
            loss.opened = !loss.opened;
        };
        $scope.addLossItem = function () {
            $scope.Model.plDetails.push({ date: "", amount: "", opened: false, type: 1 });
        };
        $scope.removeLossItemAt = function (itemToRemove) {
            if ($scope.Model.plDetails.length === 1)
                return;
            $scope.Model.plDetails.splice($scope.Model.plDetails.indexOf(itemToRemove), 1);
        };

我的html设置为:

       <div class="row" ng-if="Model.ApplicantLosses==0">
            <div class="col-xs-12">
                <div class="col-xs-12">
                    <div class="form-group">
                        <h4>Prior Loss Details</h4>
                        <div class="form-inline">
                            <div ng-repeat="loss in Model.plDetails track by $index" style="margin-top: 10px">
                                <div class="col-sm-1" style="width: 2%; margin-top: inherit;">
                                    <label id="{{$index+1}}">{{$index+1}}</label>
                                </div>
                                <div class="col-sm-2 form-group">
                                    <div class="input-group">
                                        <input type="text" class="form-control" datepicker-popup="MM/dd/yyyy" ng-model="loss.Date" id="loss-date{{$index+1}}"
                                               datepicker-pattern="((0[13578]|1[02])[-/]31[-/](18|19|20)[0-9]{2})|((01|0[3-9]|1[1-2])[-/](29|30)[-/](18|19|20)[0-9]{2})|((0[1-9]|1[0-2])[-/](0[1-9]|1[0-9]|2[0-8])[-/](18|19|20)[0-9]{2})|((02)[-/]29[-/](((18|19|20)(04|08|[2468][048]|[13579][26]))|2000))"
                                               is-open="loss.opened" max="maxDate" max-date="maxDate" date-format placeholder="MM/DD/YYYY" />
                                        <span class="input-group-btn">
                                            <button type="button" class="btn btn-default" ng-click="open($event,loss)"><i class="icon icon-calendar"></i></button>
                                        </span>
                                    </div>
                                </div>
                                <div class="form-group col-sm-9">
                                    <div class="col-sm-3" style="display: inline-table">
                                        <input type="number" ng-model="loss.amount" placeholder="$ Amount" />
                                    </div>
                                    <div class="col-sm-3" style="display: inline-table">
                                        <select id="loss-type{{$index+1}}" ng-model="loss.type" ng-options="lossType.idng-show as lossType.name for lossType in lossTypeParameters" class="form-control" required>
                                            <option value="" disabled>Loss Type</option>
                                        </select>
                                    </div>
                                    <div class="col-sm-3" style="display: inline-table">
                                        <span><a id="loss-del-item{{$index+1}}" ng-show="Model.plDetails.length > 1" style="vertical-align: middle" ng-click="removeLossItemAt(loss)"><i class="icon icon-minus-square-o icon-lg"></i>&nbsp;Remove Line</a></span>
                                        <span ng-show="Model.plDetails.length != 2 && $index+1 == Model.plDetails.length"><a id="loss-add-item{{$index+1}}" ng-click="addLossItem()"><i class="icon icon-plus-square-o icon-lg"></i>&nbsp;Add Line</a></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>