ajax 调用在 angular js 中不起作用
ajax call does not work in angular js
我的场景如下:
我有一个文本框和按钮,每当我在文本框中添加某物时,我想在 table 中添加文本,我的代码如下:
var app = angular.module('app', []);
app.factory('Service', function() {
var typesHash = [ {
id :1,
name : 'lemon',
price : 100,
unit : 2.5
}, {
id : 2,
name : 'meat',
price : 200,
unit : 3.3
} ];
var localId = 3;
var service = {
addTable : addTable,
getData : getData,
};
return service;
function addTable(name) {
typesHash.push({id:localId++, name:name, price:100,unit:1});
}
function getData() {
return typesHash;
}
});
app.controller('table', function(Service) {
//get the return data from getData funtion in factory
this.typesHash = Service.getData();
//get the addtable function from factory
this.addTable = Service.addTable;
});
plnkr如下:
现在如您所见,我在 table 的文本中添加了任何内容,一切正常,但现在我想在文本框中添加任何内容,而且我还想从 servlet 获取一些信息并添加那些 table 也是如此。所以为此我使用 ajax 调用如下:
function addTable(name) {
typesHash.push({id:localId++, name:name, price:100,unit:1});
var responsePromise = $http.get("http://localhost:8080/purchase/AddInfo");
responsePromise.success(function(data, status, headers, config) {
typesHash.push( {id:data.id,name : data.name, price : data.price,unit:2.5 });
});
}
但是当我使用它时出现以下错误:
ReferenceError: $http 未定义
有人可以帮忙吗? (请注意:这段代码是我真实代码的较小版本,我特意使用工厂,因为我需要它)
在你的控制器属性中你应该插入一个 $http 参数:
app.controller('CTRL1', function($scope, $http){
//Now your can use $http methods
})
或者如果您在服务内部使用 $http 请求方法,则在您的服务声明中插入 $http 参数
我的场景如下:
我有一个文本框和按钮,每当我在文本框中添加某物时,我想在 table 中添加文本,我的代码如下:
var app = angular.module('app', []);
app.factory('Service', function() {
var typesHash = [ {
id :1,
name : 'lemon',
price : 100,
unit : 2.5
}, {
id : 2,
name : 'meat',
price : 200,
unit : 3.3
} ];
var localId = 3;
var service = {
addTable : addTable,
getData : getData,
};
return service;
function addTable(name) {
typesHash.push({id:localId++, name:name, price:100,unit:1});
}
function getData() {
return typesHash;
}
});
app.controller('table', function(Service) {
//get the return data from getData funtion in factory
this.typesHash = Service.getData();
//get the addtable function from factory
this.addTable = Service.addTable;
});
plnkr如下:
现在如您所见,我在 table 的文本中添加了任何内容,一切正常,但现在我想在文本框中添加任何内容,而且我还想从 servlet 获取一些信息并添加那些 table 也是如此。所以为此我使用 ajax 调用如下:
function addTable(name) {
typesHash.push({id:localId++, name:name, price:100,unit:1});
var responsePromise = $http.get("http://localhost:8080/purchase/AddInfo");
responsePromise.success(function(data, status, headers, config) {
typesHash.push( {id:data.id,name : data.name, price : data.price,unit:2.5 });
});
}
但是当我使用它时出现以下错误:
ReferenceError: $http 未定义
有人可以帮忙吗? (请注意:这段代码是我真实代码的较小版本,我特意使用工厂,因为我需要它)
在你的控制器属性中你应该插入一个 $http 参数:
app.controller('CTRL1', function($scope, $http){
//Now your can use $http methods
})
或者如果您在服务内部使用 $http 请求方法,则在您的服务声明中插入 $http 参数