gpt4 book ai didi

javascript - AngularJS 如何在函数之外正确调用函数

转载 作者:行者123 更新时间:2023-11-28 05:41:28 25 4
gpt4 key购买 nike

我是 AngularJS 新手,正在尝试编写代码来从 JSON 文件中提取数据。我写了一个 GET 函数,现在想在函数外部调用 GET 函数。

我有一个 getData 函数,最后一行有 var questions = getData'~~~'。我认为我的代码中这是错误的。如何在 DataFactory 函数之外调用 getData 函数。

(function(){
angular
.module("GrammarQuiz")
.factory("DataService", DataFactory);

function DataFactory($log, $http){
var vm = this
var dataObj = {
questions: questions
};
vm.sort = sort;
vm.random = random;
vm.getData = getData;
var temp = 0;

// right now I have questions variable here
// but I want to move this to the outside of the function
//var questions = getData('data1.json');

function getData(apicall){
$log.log('begin!!!');
$http.get('api/' + apicall,
{headers:
{token: 'check!'}
}
).then(function(response){
$log.log(response.data);
questions = response.data;
}, function(response){
$log.log(response.data || "Request failed");
});
}
function sort(array) {
return array.sort(function() {
return .5 - Math.random();
});
}
function random() {
for (var key in dataObj.questions) {
dataObj.questions[key].Choices = sort(dataObj.questions[key].Choices);
}
}
random();
return dataObj;
}

var questions = DataFactory.getData('data1.json');
})();

最佳答案

正如我在评论中提到的,您需要将服务注入(inject) Controller 中。像这样的东西有效:

(function(){
var myApp = angular.module('myApp',[]);

angular
.module("myApp")
.controller("MyCtrl", MyCtrl);

MyCtrl.$inject = ["myApp.myService"]; //injects your service into your controller

function MyCtrl(dataservice) {
var vm = this;
vm.name = 'Superhero';
//calls the service
dataservice.getData();
}

angular.module("myApp").factory("myApp.myService", function() {
//exposes the service's methods
//you need this, vs the vm syntax in your service
var service = {
getData: getData
};

return service;

function getData(){
alert("S");
}
});
})();

JSFiddle:http://jsfiddle.net/Lvc0u55v/8234/

关于javascript - AngularJS 如何在函数之外正确调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38884272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com