質問

AngularJS newb here, working on my first app (with .NET on the server). I want to call the WebAPI and pass it two parameters stored in $scope, but it won't do it. If I hard code the values it works fine, but not if I use $scope.

This works:

$http.get("/api/v1/entries", { params: { workgroupId:"3", reportedOn: "5/23/1968" } })

This does not work and actually causes AngularJS to stop functioning it altogether:

$http.get("/api/v1/entries", {params: {workgroupId:$scope.params.workgroupId, reportedOn:$scope.params.reportedOn}})

This does not work either:

  $http.get("/api/v1/entries?workgroupId=" + $scope.params.workgroupId + "&reportedOn=" + $scope.params.reportedOn)

Any ideas?

役に立ちましたか?

解決

I just tried your code and it worked for me, so you must not have your variables defined.

Can you console.log your $scope.params.workgroupId and $scope.params.reportedOn variables right before your $http.get. I'm betting that they are undefined. I just put the following into one of my programs (removed the .params just for convenience; unless you're thinking that's needed for some reason?) and added the $http dependency in my controller and it worked just fine.

$scope.workgroupId = 1;
$scope.reportedOn = 2;
$http.get("/api/v1/entries", {params: {workgroupId:$scope.workgroupId, reportedOn:$scope.reportedOn}});

他のヒント

It's hard to tell for sure from what minimal sample code you have provided, but chances are that the code where your $http call is made is not within an execution context that has access to $scope.

This works (as you can see from the alert in the plnkr, the foo and bar $scope params are mapped to query params):

var app = angular.module("myApp", [function() {}])
.controller("MainCtrl", ['$scope', '$http', function($scope, $http) {
  $scope.params = { foo: "foo", bar: "bar" };
  $http.get("/", { params: { foo: $scope.params.foo, bar: $scope.params.bar }}) 
    // an error (404) is expected in this simple plnkr example
    .error(function(data, status, headers, config) {
      // but we can inspect what query params we sent in the config object
      // passed to the error callback
      alert("Params: foo = " + config.params.foo +
           " & bar = " + config.params.bar);
    });
}]);

For a better explanation, please provide more detail about your problem, including sample code of your controller (and whatever component you are using for the $http call).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top