【问题标题】:Assinging a scope variable to data in http service将范围变量分配给 http 服务中的数据
【发布时间】:2019-08-01 06:20:17
【问题描述】:
app.controller('contentixaeng', function ($scope, $http)  {

    $scope.subject = function(){
        $scope.code=101;
    };

  $http({
    method: "POST",
    data:{
        'subj_code':$scope.code, 'action':'singledata'
    },
    url: "pages/Entries/connectixa.php"
  }).then(function mySuccess(response) {
    $scope.users = response.data;
  }, function myError(response) {
    $scope.error = response.data;
  });
});

我正在尝试将 $scope.code 的值传递给 HTTP 服务中的数据。它无法正常工作,并且没有数据值显示为输出。相反,我收到错误“ng-repeat dupes”。

通过这一行调用函数主题

<li class="nav-item" ng-contoller="contentixaeng"><a class="nav-link" href="#" ui-sref="ixaeng" ng-click="subject()" >English</a></li>

如果我更改如下所示的代码,那么它可以工作

app.controller('contentixaeng', function ($scope, $http)  {

    $scope.subject = function(){
        $scope.code=101;
    };

  $http({
    method: "POST",
    data:{
        'subj_code':101, 'action':'singledata'
    },
    url: "pages/Entries/connectixa.php"
  }).then(function mySuccess(response) {
    $scope.users = response.data;
  }, function myError(response) {
    $scope.error = response.data;
  });
});

我希望根据点击事件将不同的数据传递给数据库搜索。

【问题讨论】:

    标签: angularjs angularjs-directive angular-ui-router angular-material


    【解决方案1】:

    http 请求在控制器创建时立即发送。此时$scope.code 尚未设置。

    试试这样的:

    app.controller('contentixaeng', function ($scope, $http)  {
    
      $scope.subject = function(){
          $scope.code=101;
          callBackend();
      };
    
      function callBackend() {
        $http({
          method: "POST",
          data:{
            'subj_code':$scope.code, 'action':'singledata'
          },
          url: "pages/Entries/connectixa.php"
        }).then(function mySuccess(response) {
            $scope.users = response.data;
        }, function myError(response) {
            $scope.error = response.data;
        });
      });
    }
    

    这样,http 请求只有在显式调用 callBackend 方法时才会发送。

    【讨论】:

      【解决方案2】:

      如果您收到 ng-repeat dupes 错误,这意味着您在 $scope.users 中有重复的条目 - 请尝试调试它并查看那里发生了什么。此外,您可以使用track by 选项,如下所示:

      ng-repeat="user in users track by $index"
      

      它将确保每个user 都将被视为唯一实体,即使您在$users 变量中有重复条目。

      另一件事是,这段代码在哪里运行?我在您提供的代码中的任何地方都没有看到它

      $scope.subject = function(){
          $scope.code=101;
      };
      

      【讨论】:

      • 我已经添加了调用该函数的代码。请立即检查上述问题
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多