【问题标题】:ng-click or ng-change don't save arrayng-click 或 ng-change 不保存数组
【发布时间】:2017-05-05 16:50:37
【问题描述】:

我有一个新的拍卖表格。用户必须插入所有请求的字段,然后通过单击“邀请人”按钮可以邀请其他已保存的用户或可以通过电子邮件邀请人。电子邮件部分工作正常。但是用户部分给了我一些问题。

html部分:

          <div ng-show="showBid" class="panel panel-default" ng-controller="NewAuctionController">
<div class="panel-heading">Invite Members</div>
<div class="panel-body">
    <ul class="list-group" ng-repeat="user in users">
        <li class="col-md-4" id="userlist" ng-hide="user.name == profile">
            <img ng-src="{{user.img}}" class="userImage">
            <div class="username"> {{user.name}}</div>
            <div class="userrole"> {{user.role}} </div>
            <div class="usercompany">{{user.company}}</div>
            <input type="checkbox" ng-model="user.isChecked" ng-click="insertinvited(user)">

</li>
</ul>

以上部分我也尝试使用 ng-change,但它是相同的。 insertinvited() 是:

                $scope.invitations=[];

$scope.insertinvited= function (user) {

    if(user.isChecked) {
        $scope.invitations.push(user.name);
    } else {
        var toDel = $scope.invitations.indexOf(user.name);
        $scope.invitations.splice(toDel,1);
    }
    console.log($scope.invitations);

};

在控制台中这是可行的,因为当我选中该框时,数组被正确推送

但是当我在这里尝试使用该数组时:

<div ng-show="showBid" class="panel panel-default" >
    <div class="panel-heading">Members Selected:</div>
    <div class="panel-body">
        <ul class="list-group">
            <li class="list-group-item" ng-repeat="invitation in invitations">
                <div class="listmail"> {{invitation}}</div>

            </li>
        </ul>
    </div>
</div>

数组似乎是空的,事实上,当我将数组传递给控制器​​并尝试执行 console.log 时,数组是空的。 谁能帮帮我?

已编辑

这是我所有的html代码:

                 <form  ng-controller="NewAuctionController" 
           name="myform">
     <div>
       <div ng-hide="showBid">
      <div ng-show="uploading" class="progress">
       </div>
        <label class="btn" style="background-color: #858892">
        Browse
        <input type="file" ng-disabled="uploading" file-model="file.upload" name="myfile" style="display: none;" onchange="angular.element(this).scope().photoChanged(this.files)">
    </label>
    <br>
    <br>
    <br>
    <img class="mythumbnail" ng-src="{{ thumbnail.dataUrl || default }}">
<br>
<br>
<div ng-show="message">
    <div ng-class="alert">{{ message }}</div>
</div>
<div class="form-group" id="productname">
        <label for="exampleInputName1">Product Name</label>
        <input type="text" class="form-control" id="exampleInputName1" placeholder="Enter Product" ng-model="productTitle" >
</div>
    <br>
    <div class="form-group">
    <label for="exampleInputdescription1"> Description:</label>
    <input type="text" class="form-control" id="exampleInputdescription1" placeholder="Enter Description" ng-model="productDescription" >
</div>
 <div class="form-group">
    <label> Expiration Date:</label><br>
    <input type="date" class="form-control" name="expiration date" ng-model="endtime" ><br>
</div>
 <div  class="quantity">
    <label>Quantity:</label><br>
    <input type="number" name="quantity"  ng-model="quantity" placeholder="u" class="form-control" ><br>
</div>
 <div class="Warranty">
    <label>Warranty (days):</label><br>
    <input type="number" name="warranty" class="form-control" ng-model="warranty" placeholder="days" ><br>
</div>
 <div class="form-group">
    <label>Minimum Price:</label><br>
    <input type="number" name="minimum price" id="min" ng-model="minPrice" placeholder="€" class="form-control" ><br>
</div>
<div class="form-group">
    <label>Buy-Now Price:</label><br>
    <input type="number" name="minimum price" id="min" ng-model="productbuynow" placeholder="€" class="form-control" ><br>
</div>
<div class="form-group">
    <label>Location of the goods:</label><br>
    <input type="text" name="location" id="country" ng-model="Country" placeholder="Country" class="form-control" ><br>
    <input type="text" name="Town" id="town" ng-model="Town" placeholder="Town" class="form-control" ><br>
    <input type="text" name="address" id="address" ng-model="Address" placeholder="Address" class="form-control" ><br>
    <input type="text" name="Postal code" id="postalCode" ng-model="PostalCode" placeholder="Postal Code" class="form-control" ><br>
</div>
<div class="form-group">
    <label>Terms of payment: </label><br>
    <select ng-model="payment">
        <option value="Letter of credit">Letter of credit</option>
        <option value="Cash in advance">Cash in advance</option>
        <option value="Confirmed Irrevocable Credit">Confirmed irrevocable Credit</option>
    </select><br>
</div>
<div class="form-group">
    <label>Terms of Delivery: </label><br>
    <select ng-model="delivery">
        <option value="Carriage Paid To">Carriage Paid To</option>
        <option value="Free Carrier">Free Carrier</option>
        <option value="Confirmed Irrevocable Credit">Ex Works</option>
    </select><br>
</div>
           <input class="savebutton" type="submit" value="Invite People" ng-click="clickToOpen5()"><br>

                   <div ng-show="showBid" class="panel panel-default" ng-controller="NewAuctionController">
             <div class="panel-heading">Invite Members</div>
          <div class="panel-body">
        <ul class="list-group" ng-repeat="user in users">
          <li class="col-md-4" id="userlist" ng-hide="user.name == profile">
            <img ng-src="{{user.img}}" class="userImage">
            <div class="username"> {{user.name}}</div>
            <div class="userrole"> {{user.role}} </div>
            <div class="usercompany">{{user.company}}</div>
            <input type="checkbox" ng-model="user.isChecked" ng-change="insertinvited(user)">
              </li>
              </ul>
             </div>
            <div class="panel-heading">Members Selected:</div>
            <div class="panel-body">
            <ul class="list-group">
            <li class="list-group-item" ng-repeat="invitation in invitations">
                <div class="listmail"> {{invitation}}</div>
        </li>
        </ul>
    </div>

                 <div class= "insertmail" ng-show=" showBid ">
         Or Insert E-mail:<br>
       <input type="email" name="emailaddress" ng-model="emailaddress">


                  <div ng-show="showBid" class="panel panel-default" >
              <div class="panel-heading">Mail Inserted:</div>
               <div class="panel-body">
            <ul class="list-group">
              <li class="list-group-item" ng-repeat="mail in mails">
            <div class="listmail"> {{mail}}</div>
           </li>
           </ul>
          </div>
        </div>
                 <button ng-show="showBid" class="savebutton" ng-click="saveauction(profile)">SAVE</button><br>
           </div>
           </form>

这就是我的所有控制器:

              angular.module('NewAuctionCtrl', ['ngDialog', 'fileModelDirective', 'uploadFileService']).controller('NewAuctionController', ['$scope','$http' ,'ngDialog','uploadFile', '$timeout' , function($scope, $http, ngDialog, uploadFile,  $timeout){
$scope.file = {};
$scope.message = false;
$scope.alert = '';
$scope.photoChanged = function (files) {
    if (files.length > 0 && files[0].name.match(/\.(png|jpeg|jpg|pdf)$/)) {
        $scope.uploading = true;
        var file = files[0];
        var fileReader = new FileReader();
        fileReader.readAsDataURL(file);
        fileReader.onload = function(e) {
            $timeout(function() {
                $scope.thumbnail = {};
                $scope.thumbnail.dataUrl = e.target.result;
                $scope.uploading = false;
                $scope.message = false;
            });
        };
    } else {
        $scope.thumbnail = {};
        $scope.message = false;
    }
};
$http.get('/api/users').then(function(Users) {
    $scope.users = Users.data;
});

$scope.mails = [];
$scope.emailaddress = '';

$scope.insertmail = function () {

    $scope.mails.push($scope.emailaddress);
    $scope.emailaddress = '';
};
$scope.invitations = [] ;
$scope.insertinvited= function (user) {
   if(user.isChecked) {
        $scope.invitations.push(user.name);
    } else {
        var toDel = $scope.invitations.indexOf(user.name);
        $scope.invitations.splice(toDel,1);
    }
    console.log($scope.invitations);
};
$scope.saveauction = function (user) {

    console.log($scope.invitations);

    var array = {
        param1: $scope.productTitle,
        param2: $scope.productDescription,
        param3: $scope.endtime,
        param4: $scope.minPrice,
        param5: $scope.productbuynow,
        param6: user,
        param7: $scope.quantity,
        param8: $scope.warranty,
        param9: $scope.Country,
        param10: $scope.Town,
        param11: $scope.Address,
        param12: $scope.PostalCode,
        param13: $scope.payment,
        param14: $scope.delivery,
        param15:$scope.invitations
    };
        $scope.uploading = true;
        uploadFile.upload($scope.file).then(function (data) {
            if (data.data.success) {
                $scope.uploading = false;
                $scope.alert = 'alert alert-success';
                $scope.message = data.data.message;
                $scope.file = {};
                $http.post('/api/newauction', array)
                    .then(
                        function () {
                            swal(
                                'Good job!',
                                'New Auction is created',
                                'success'
                            )

                        });
               $scope.sendmail();
            }
            else {
                $scope.uploading = false;
                $scope.message = data.data.message;
                swal(
                    'Oops...!',
                    $scope.message,
                    'error'
                );
                $scope.file = {};
            }
        });
    };
    $scope.clickToOpen5 = function () {
    $scope.showBid = !$scope.showBid;
};
  $scope.sendmail = function (){
    var address = $scope.mails;
    console.log(address);

    if(address[0]) {
        $http.post('/api/sendmail/', {address: address}).then(function (err) {
            if (err)
                console.log(err);
        });
    }


};

});

【问题讨论】:

  • 我认为,在这一行$scope.invitations.indexOf(user); 你应该使用$scope.invitations.indexOf(user.name);
  • 是的,你说得对,我错过了。但是那部分有效并且数组被正确填充。但是当我以后想使用这个数组时,就像它是空的一样

标签: javascript angularjs arrays checkbox


【解决方案1】:

你应该把 ng-click 改成 ng-change

 <input type="checkbox" ng-model="user.isChecked" ng-change="insertinvited(user)">

在你们的del中,我认为它应该

var todel =$scope.invitations.indexOf(user.name);
  $scope.invitations.splice(toDel,1);

【讨论】:

  • 是的,你是对的,但问题仍然存在。当我稍后使用 html 中的数组来显示选定的成员时。它什么也没显示
  • @MarcoPagano 你能创建一个 plnkr 吗?
  • @MarcoPagano 你应该发布代码有问题。很难阅读完整的代码。这是我创建的 plnkr。希望对plnkr.co/edit/Y8QRiU1mSESAXkHZ6GKQ?p=preview有帮助
  • 我修好了。这只是因为我在模板中有 2 次调用“ng-controller="NewAuctionController"”。太傻了,看不见
  • @MarcoPagano 所以这个问题已经解决了吗?请投票
【解决方案2】:

这可能是 Angular JS 中作用域继承的问题。

尝试进行以下更改:

在控制器中将this 保存到某个参数,例如:

var vm = this;

现在使用vm.invitations 代替$scope.invitations

ng-repeat 中使用:

ng-repeat="invitation in vm.invitations"

【讨论】:

  • 不,没有任何改变。这仍然有效,但是当我尝试在另一个函数中使用 $scope.invitations 时,数组是空的,而如果我在 html 中将它用作 vm.invitations,则没有任何显示
  • 在另一个函数中,只需要使用vm.invitations即可。
  • 邀请人按钮的类型是什么?
【解决方案3】:

每次点击都会清除数组。

删除此语句:

$scope.invitations = [];

并将其移动到控制器的主体;那么它应该可以工作(特别是如果您使用的是ng-change)。

【讨论】:

  • $scope.invitations 不在函数内部,而是在函数外部
【解决方案4】:

这是由于 javascript 中的原型继承。 在控制器内部使用var vm= this 和 将控制器中的$scope.invitations 重命名为vm.invitations,将html 中的invitations 重命名为vm.invitations。 将解决问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    相关资源
    最近更新 更多