I have a json object in my express.js routes file and in order to parse it, I am guessing that the best way would be to send to my Angular controller to be looped in my view.
routes/myaccount.js
router.post('/', function(req, res) {
// form submitted
var email = req.body.email
var password = req.body.password
login.returnSessionToken(email, password, (token) => {
console.log("return token: ", token)
var logged = require('../js/index')
logged.returnUserData(token, (myData) => {
res.render('myaccount', { myDataFromRoutes:myData });
})
},
(fail) => {console.log(fail)})
})
controller.js
var controllers = angular.module('myApp.controllers', []);
controllers.controller('IndexController', ['$scope', function($scope) {
$scope.data= myDataFromRoutes; //how do I get the JSON object from my routes and pass it here?
}]);
myaccount.html
<body ng-app="myApp">
<div ng-controller="IndexController">
<li ng-repeat="d in data">
{{ d }}
</li>
</div>
</body>
Is the structure right? I can't figure how to make my express routes communicate with my angular controller.
Any help will be much appreciated. Thanks!
Since you are not using $http to AJAX the JSON object, you can use ngInit. This is one of the few intended uses of ngInit. Use Jade or whatever server template engine you have to interpolate the JSON object in the ng-init directive:
<body ng-app="myApp">
<div ng-controller="IndexController" ng-init="data = #{JSON.stringify(myDataFromRoutes)}">
<li ng-repeat="d in data">
{{d}}
</li>
</div>
</body>
Since you are operating inside the controller's scope, the data variable will also be available in your controller as $scope.data.
Alternatively, (probably better, actually) you can interpolate directly in the JavaScript. But this, won't work for JS included as a file. It will have to be an inline script:
<script>
var controllers = angular.module('myApp.controllers', []);
controllers.controller('IndexController', ['$scope', function($scope) {
$scope.data= #{JSON.stringify(myDataFromRoutes)};
}]);
</script>
NOTE: Recent versions of Pug have replaced the above interpolation syntax with the following:
ng-init="data = `${JSON.stringify(myDataFromRoutes)}`"