如何将更新的字段值传递给函数(内联编辑和更新)

时间:2017-06-02 05:46:04

标签: angularjs

我正在进行内联编辑和更新 EditCancel功能正常运行。但是在更新时无法将更新的字段值传递到update函数,它在undefined中显示console.log。这是什么问题?

<body ng-app="intranet_App">
  <table class="table table-hover table-bordered" id="mydata" ng-controller="myCtrl">
    <thead class="colorBlue">
      <tr>
        <th>S.No</th>
        <th>Name</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody id="">
      <tr ng-repeat="x in roleList | filter:searchText" ng-model="x.Id">
        <td>{{x.Id}}</td>
        <td>
          <span ng-hide="editMode">{{x.name}}</span>
          <input type="text" ng-show="editMode" ng-model="x.name" />
        </td>
        <td>
          <i class="edit fa fa-pencil-square-o" id="edit{{x.Id}}" ng-click="editMode = true;edit(x.Id)" ng-hide="editMode"></i>
          <i class="update fa fa-floppy-o" id="update{{x.Id}}" ng-hide="true" ng-show="editMode" ng-click="update(x.name);editMode = false"></i>
          <i class="editCancel fa fa-times" id="editCancel{{x.Id}}" ng-click="editMode = false" ng-hide="true" ng-show="editMode"></i>
        </td>
      </tr>
    </tbody>
  </table>
</body>
<script>
  var app = angular
    .module("intranet_App", [])
    .controller('myCtrl', function($scope, $http) {
      $scope.updateItem = [];
      $scope.updatedList = function(val) {
        $scope.updateItem.push(val);
        $scope.json = angular.toJson($scope.val);

      }
      $http.post("/Admin/getRolesList")
        .then(function(response) {
          $scope.roleList = response.data;
        });
      //$scope.edit=function(val){
      //    $scope.editing = $scope.items.indexOf(val);
      //}
      $scope.update = function(val) {
        console.log(val)
        $scope.updatedList(val);
        var requestHeaders = {
          "Content-type": 'application/json'
        }
        var httpRequest = {
          method: 'post',
          url: '/Admin/RoleUpdate',
          headers: requestHeaders
        };
        httpRequest.data = $scope.json;
        $http(httpRequest).then(function(response) {
          alert("success")
        })
      }
      $scope.cancel = function(val) {
      }
    })
</script>

1 个答案:

答案 0 :(得分:1)

updatedList function中,您已$scope.val,但应该是val

由于您要从函数参数访问val,因此它不在scope,因此$scope.val将未定义

angular.toJson($scope.val);更改为angular.toJson(val);

$scope.updatedList = function (val) {
    $scope.updateItem.push(val);
    $scope.json = angular.toJson($scope.val);
    console.log($scope.json)
}

应该是,

$scope.updatedList = function (val) {
    $scope.updateItem.push(val);
    $scope.json = angular.toJson(val);
    console.log($scope.json)
}

根据您的需要进行更新:

$scope.updatedList = function (val) {
   $scope.updateItem.push(val);
   $scope.json = angular.toJson(val);
   if($scope.json)
    {
      $scope.json = { "name": $scope.json }   
    }
    console.log($scope.json)
}