Pass a input field value into angularjs $resource

2019-09-14 02:58发布

问题:

===========================================================================

Update 1 Fixed code produce new error of

ReferenceError: inputName is not defined

on the line of

 inputName:inputName,

Below is the new code

<script src="/library/angularjs/1.2.0-rc.3/angularjs.js"></script>
<script src="/library/angularjs/1.2.0-rc.3/angular-route.js"></script>
<script src="/library/angularjs/1.2.0-rc.3/angular-resource.js"></script>
<script>
var app= angular.module('myApp', ['ngRoute', 'ngResource']);
app.factory('Greeter', ['$resource',function($resource){
  return $resource(
    'http://123.com/processor.php',
    {
      inputName:inputName,
      callback: 'JSON_CALLBACK'

    },
    {
      query: {method:'GET',isArray:true}
    });
}]);

app
.controller('MyCtrl', ['$scope', 'Greeter',
  function($scope,Greeter){
  /*alert("yes");*/
  $scope.greet = function(){
    //alert("greetttt");
    alert("before greeeter"+$scope.inputName);
    Greeter.query(
      {inputName:$scope.inputName},
      function(response){
        alert(response[0].myCodeId);
        $scope.output=response[0].myCodeId;
      }
    );
  };
}]);
</script>
<div ng-app="myApp">
  <div ng-controller="MyCtrl">
  Your name:
    <input type="text" ng-model="inputName" name="myInput" value="World"/>
    <button ng-click="greet()">greet</button>

  <div>
  Test Output Here

    {{output}}

  </div>
  </div>
</div>

I wonder where do I get it wrong?

Thanks

回答1:

http://plnkr.co/edit/CKgWrson3IbMugRKdX5p?p=preview

A few problems that I fixed that others pointed out in the comment.

Remove $scope from factory. Here you are getting a generic $scope object but not the actual scope. You will get that in the controller. When you call angular resource with query() the first argument is already the param. But you can specify the common params like you did before.

function($resource) {
  return $resource('mocked-resource.json', {
    callback: 'JSON_CALLBACK'
  }, {
    query: {
      method: 'GET',
      isArray: true
    }
  });

Hope this helps.



回答2:

inputName:inputName,

second inputName refer to not existing variable. I think this line can be removed at all. But it depends on what you want to achieve.