Javascript AngularJs-在控制器中使用工厂函数
我是AngularJs新手,在尝试避免在不同的控制器中编写相同的代码时遇到了一个问题 我已经创建了一个工厂,它应该保存所有函数,而控制器能够使用这些函数,并将一个函数从控制器移动到该工厂。 我创建了一个函数,它应该发布表单中的数据,但当我点击它执行时,实际上什么都没有发生 我在google和stackoverflow上搜索了很长时间,没有找到任何适合我的问题 有什么我错过或做错的吗 工厂:Javascript AngularJs-在控制器中使用工厂函数,javascript,angularjs,Javascript,Angularjs,我是AngularJs新手,在尝试避免在不同的控制器中编写相同的代码时遇到了一个问题 我已经创建了一个工厂,它应该保存所有函数,而控制器能够使用这些函数,并将一个函数从控制器移动到该工厂。 我创建了一个函数,它应该发布表单中的数据,但当我点击它执行时,实际上什么都没有发生 我在google和stackoverflow上搜索了很长时间,没有找到任何适合我的问题 有什么我错过或做错的吗 工厂: (function(){ angular.module("myApp").factory('appS
(function(){
angular.module("myApp").factory('appServicesProvider',function( $http ) {
var restURL = "http://localhost:8080/Project/rest/api/";
function postFunction(data){
$http.post(restURL, JSON.stringify(data)).then(
function(response){
}
);
}
return{postFunction:postFunction}
});
})();
控制器:
(function() {
angular.module("myApp")
.controller("AdminController",function($scope, $http, appServicesProvider) {
$scope.restURL = "http://localhost:8080/Project/rest/api/";
)}; // There's more code but it's irrelevant to the function I'm talking
about
(function() {
angular.module("myApp")
.controller("AdminController",function($scope, $http, appServicesProvider) {
$scope.restURL = "http://localhost:8080/Project/rest/api/";
$scope.postFn = function(data) {
appServicesProvider.postFunction(data);
};
)}; // There's more code but it's irrelevant to the function I'm talking
about
HTML:
后置功能
未调用appServicesProvider
的postFunction
的问题,因为您尚未在$scope
上公开appServicesProvider
服务。简而言之,$scope
中公开的任何内容都可以在html上访问
angular.module("myApp")
.controller("AdminController",function($scope, $http, appServicesProvider) {
$scope.appServicesProvider = appServicesProvider
)};
上面的内容只会解决您的问题,但这不是一个好办法,因为您不必要地公开了HTML上的所有服务。而是通过创建自己的方法postFunction
在$scope
上只公开所需的服务方法
angular.module("myApp")
.controller("AdminController",
function($scope, $http, appServicesProvider) {
$scope.postFunction = function (data) {
appServicesProvider.postFunction(data)
}
}
);
HTML
ng-click="postFunction(data)"
ng单击
应调用控制器内的范围函数,而不是试图直接调用工厂内的方法。该控制器函数将调用工厂方法。例如:
控制器:
(function() {
angular.module("myApp")
.controller("AdminController",function($scope, $http, appServicesProvider) {
$scope.restURL = "http://localhost:8080/Project/rest/api/";
)}; // There's more code but it's irrelevant to the function I'm talking
about
(function() {
angular.module("myApp")
.controller("AdminController",function($scope, $http, appServicesProvider) {
$scope.restURL = "http://localhost:8080/Project/rest/api/";
$scope.postFn = function(data) {
appServicesProvider.postFunction(data);
};
)}; // There's more code but it's irrelevant to the function I'm talking
about
HTML:
后置功能
啊!!我知道你在那里做了什么:)非常感谢@我的错。我的代码有输入错误。我纠正了。你能试试吗?现在它的代码和凯尔建议的一样,可以工作:)谢谢@是的。。我以前也有过,但没有更改函数名:)我没有从他的代码中复制:p