Javascript函数同步

时间:2016-05-06 10:22:31

标签: javascript angularjs undefined user-input angular-promise

我目前正在为大学做最后一年的项目。我正在创建一个从数据库中获取数据的UI,然后使用用户输入操作数据以生成图形。

事件的顺序是:DataCtrl使用HTTP get从数据库中获取数据。然后,它将数据存储在dataFactory中。然后RadioCtrl将查找用于选择的用户输入。然后将其存储在userFactory中。

我想要做的是创建一个函数来比较dataFactory中的数据和来自userFactory的输入,但是不断发现dataFactory是未定义的。我知道我需要实现某种承诺/延迟,但我从来没有使用过,我正在学习Javascript,所以我不太清楚如何做到这一点,或者它是否是最好的方式去做它。我的代码如下,任何问题或建议将不胜感激。

app.factory('dataFactory', function() {
var data = [];
var ids = [];
var areas = [];
var speakers = [];
var nonSpeakers = [];
var notStated = [];
var highestEd = [];
var gender = [];
var labourPop = [];

//Array of functions for data
var dataService = {};

dataService.getData = function(response) {
    data.push(response);
    response.forEach(function(element){
        ids.push(element.id);
        areas.push(element.area);
        labourPop.push(element.labourPop);
        speakers.push(element.irishSpeakers);
        nonSpeakers.push(element.nonIrishSpeakers);
        notStated.push(element.notStated);
        highestEd.push(element.highestEd);
        gender.push(element.gender);
    })
};

dataService.list = function(){
    return data;
}
return dataService;
});

app.factory('userFactory', function (){
var education;
var gender;
var location;
var graph;
//Add user input functions here
var userService = {
};

userService.filter = function(dataFactory) {

     dataFactory.ids.forEach(function(element){
        if(education ===dataFactory.highestEd[element])
            graph.push(dataFactory.data[element]);
    })

    console.log(dataFactory.ids);
};

return userService;
});

app.controller('GraphCtrl', function(dataFactory, userFactory){
userFactory.filter(dataFactory);
});

app.controller ('DataCtrl', function(dataFactory, $http) {
$http.get("http://localhost:6698/ngdemo/rest/users")
.then(function(response) {
    dataFactory.getData(response.data);
})
});

app.controller('RadioCtrl', function(userFactory) {
userFactory.education = {
    education : ''
};
userFactory.gender = {
    gender : ''
};
userFactory.location = {
        location : ''
};      
});

2 个答案:

答案 0 :(得分:0)

我认为你应该添加

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

到你的 app.js ,那么你的HTML应该是这样的:

    <html ng-app="myApp">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS </title>

    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="DataCtrl">

  </body>


</html>

答案 1 :(得分:0)

您可以尝试使用 承诺

var compare = new Promise( function(resolve, reject){
  // here goes synchronous code

  if ( /* compare string */ ) {
    resolve( data );
  } else {
    reject( error );
  }
});

compare.then( function(data){
  /* do something with data */
}).catch( function( error ){
  throw new Error( error )
});