ng-click或ng-change不保存数组

时间:2017-05-02 11:08:55

标签: javascript angularjs arrays checkbox

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

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);
        });
    }


};

});

4 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

这可能是角度JS中范围继承的问题。

尝试进行以下更改:

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

var vm = this;

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

并在ng-repeat中使用:

ng-repeat="invitation in vm.invitations"

答案 2 :(得分:0)

每次点击都会清除阵列。

删除此声明:

$scope.invitations = [];

并将其移至控制器的主体;然后它应该工作(特别是如果你使用ng-change)。

答案 3 :(得分:0)

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