AngularJs将参数传递给服务

时间:2017-11-01 11:20:35

标签: angularjs model-view-controller

我想通过post方法输入Id,并从数据库中获取该Id的数据。我目前收到错误" employeeID未定义"在我的控制器代码中。

控制器代码:

$scope.employeeID = '10';


function test() {
    var getData = myService.getEmployee(employeeID);
    getData.then(function (emp) {
        $scope.employees2 = emp.data;

    }, function () {
        alert('Error in getting records');
    });
}

test(employeeID);

服务代码:

this.getEmployee = function (employeeID) {
    var response = $http({
        method: "post",
        url: "Home/getEmployeeByNo",
        params: {
            id: JSON.stringify(employeeID)
        }
    });
    return response;
}

HomeController代码:

    public JsonResult getEmployeeByNo(string EmpNo)
    {
        using (InsiteEntities dataContext = new InsiteEntities())
        {
            int no = Convert.ToInt32(EmpNo);
            var employeeList = dataContext.Employee.Find(no);
            return Json(employeeList, JsonRequestBehavior.AllowGet);
        }
    }

2 个答案:

答案 0 :(得分:1)

更改

 var getData = myService.getEmployee(employeeID);

 var getData = myService.getEmployee($scope.employeeID);

答案 1 :(得分:1)

您应该在EmpNo对象中传递id参数,以便该网址形成params

Home/getEmployeeByNo?EmpNo=123

this.getEmployee = function (employeeID) { var response = $http({ method: "post", url: "Home/getEmployeeByNo", params: { EmpNo: employeeID //changed to `EmpNo` } }); return response; } employeeID $scope中所描述myService.getEmployee($scope.employeeID);中描述 public void render(Context context, ImageResource value, SafeHtmlBuilder sb){ sb.appendHtmlConstant("<div qtip='TOOLTIPVALUE'>"); super.render(context, value, sb); sb.appendHtmlConstant("</div>"); }