I'm now building up a web app using Node.js, AngularJS and either MySQL or MongoDB. However, when I tried to use AngularJS with a controller which includes datasets fetched from database, I wonder where I should write the code in...
I'm now writing in the following code (search.ejs, not including full portion (such as html
tag)):
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="/javascripts/searchController.js"></script>
<div ng-app class="row" ng-controller="searchCtrl">
<input ng-model="query">
<ul class="search">
<li ng-repeat="i in list" | filter:query">
<a href="{{i.url}}">{{i.name}}</a>
</li>
</ul>
</div>
And I want to fetch data in list
from database and use it. So here's searchController.js
file:
function searchCtrl($scope){
$scope.list = [
{
'name': 'Michael',
'url': 'mic'
},
{
'name': 'Bob',
'url': 'bob'
}
]
}
However, what I want to do is instead of writing out data in the $scope.list
variable manually, use data in database of either MySQL or MongoDB. (And MySQL is my preferred language, but MongoDB seems like the better in this case, I think.) So how can I connect to DB?
I also have one file called search.js
, which is the following one:
exports.index = function(req, res) {
res.render("search", {
}, function(err, res){
res.render("index", {
content: res
});
});
}
And finally, I also want to hear from you whether I should first save data from database to any file and use it by opening and closing the file, or I should directly connect to database whenever the request comes to fetch data, in terms of performance and security issues, (the data in database would be updated every day, so I have to run a script to automatically recreate the served file anyway).
Thanks.
saving to a file
is as follows: 1) fetch data from DB and save its result to a file. 2) Load the saved file insearchController.js
and map its content to the value of$scope.list
variable. 3) finally, access the variable from withinsearch.ejs
file. – user2360798 Nov 3 at 21:53