meanjs route to server controller - angularjs

i am trying to add a new method to my controller "matches.server.controller" names listTeams.
I have added a new route to the matches.server.route.js file like this
'use strict';
/**
* Module dependencies.
*/
var users = require('../../app/controllers/users.server.controller'),
matches = require('../../app/controllers/matches.server.controller');
module.exports = function(app) {
// Match Routes
app.route('/matches/listTeams') <-- new route added here !!
.get(matches.listteams);
app.route('/matches')
.get(matches.list)
.post(users.requiresLogin, matches.create);
app.route('/matches/:matchId')
.get(matches.read)
.put(users.requiresLogin, matches.hasAuthorization, matches.update)
.delete(users.requiresLogin, matches.hasAuthorization, matches.delete);
// Finish by binding the matches middleware
app.param('matchId', matches.matchByID);
};
this is the method in my server controller:
exports.listteams = function(req, res) {
res.json(1);
};
In matches.client.controller i call the method like this:
$scope.listteams = function(){
$scope.teams = Matches.get('matches/listTeams').success(function(data){
var d = data;
}).error(function(data){
var d = data;
});
however when i debug i always come in the list method of matches and not in listTeams method
What am i doing wrong?

Maybe it's because you are duplicating the path name
All parameters that goes after '/matches/' is handling by
app.route('/matches/:matchId')
.get(matches.read)
.put(users.requiresLogin, matches.hasAuthorization, matches.update)
.delete(users.requiresLogin, matches.hasAuthorization, matches.delete);
and perceiving like argument of'/:matchId'
In your case: find me team with id "listTeams"
Try to rename your path from matches to smth else like
module.exports = function(app) {
// Match Routes
app.route('/smthelse_not_matches/listTeams') <-- new route added here !!
.get(matches.listteams);

Related

Can an "it" block be called multiple times in different spec files using Page Objects

I am fairly new to Protractor and Page Objects. I am trying to get the header to show across multiple pages. I have a header_page.js and a header_spec.js. I can verify that the header is present once within the header_spec.js (which is presently only pointing to the home page). What I would like to do is call the test for the header each time I visit a page.
var HomePage = require('../pages/home_page.js');
var HeaderPage = require('../pages/header_page.js');
describe('When visiting a page'. function(){
var headerPage = new HeaderPage();
var inbox_page = new HomePage();
beforeEach(function () {
inbox_page.visit();
});
it('header menu selector should be present', function(){
header_menu = headerPage.hdr_menu;
header_menu.click();
expect('header_menu').not.toBe(null);
});
});
});
I am not sure how to call this test from page2_spec.js..page3_spec.js as each page is different but should all contain a header. I am trying to avoid code duplication and would like to avoid calling the "it" block from each page. Do I use a helper file or can I move the it block inside the header_page.js..currently looks like this:
module.exports = function(){
this.hdr_menu = element(by.css('#pick-group-btn'));
this.hdr_img = element(by.css('PeopleAdmin logo'));
}
you can call a test spec to other specs by wrapping your spec in a function and exporting it "requiring" that module So in your case you can export header_spec.js to other modules such as page2_spec.js or page3_spec.js by :
var HomePage = require('../pages/home_page.js');
var HeaderPage = require('../pages/header_page.js');
var commHeader = function(){
describe('When visiting a page'. function(){
var headerPage = new HeaderPage();
var inbox_page = new HomePage();
beforeEach(function () {
inbox_page.visit();
});
it('header menu selector should be present', function(){
header_menu = headerPage.hdr_menu;
header_menu.click();
expect('header_menu').not.toBe(null);
});
});
});
}
module.exports = commHeader;
Then in you page2_spec.js file you can import this module like this :
var commHeader = require('your path to spec/commHeader.js');
describe('When visiting page 2 validate Header first'. function(){
var headerTest = new commHeader();
headerTest.commHeader();
it('page 2 element validations', function(){
//here the page 2 test goes
});
});
});

How To Get Constant Inside ui-router (Angular) state function

I want to reference a "constant" that is defined outside this state function but if I try to pass it in as a provider it errors because constants are not providers. That is, I want to do something like:
var exports = module.exports = function ($stateProvider,configData) { ...
But that fails. How can I get my javascript variable baseDirectory passed in.
The bigger problem is that the webroot is not always at the same url. sometimes it is /ng and sometimes it is just / and I want to be able to set that as a config someplace I can load into a config file (not hard code into the state function.
var exports = module.exports = function ($stateProvider) {
$stateProvider.state('home', {
url: baseDirectory + '/home',
templateUrl: '/templates/home/home.html',
controller: 'HomeController',
});
};
exports.$inject = ['$stateProvider'];
I got the same issue, what I did, is to build a constant in the app, and replace them with new value in gulp task when the base url changed.
It had many apps, so my idea is dumb and simple, just find and replace the value of the content in the app by the new value input from gulp task configuration.
It's not smart, but works.
In the example, I have three apps in /clinic, /panel, /company, and for each of them, it had a build.js in it.
The build.js will build the app, and replace the constant value.
I have many apps, so I do this:
var gulp = require('gulp');
var concat = require('gulp-concat');
var taskBuildClinic = require("./clinic/build");
var taskBuildPanel = require("./panel/build");
var taskBuildCompany = require("./company/build");
var migrate = require("./laravel/migrate");
var env = {
'dev': {
EndpointBaseUrl: "'/admin/public/';",
TemplateBaseUrl: "'/admin/public';"
}
};
// ./node_modules/.bin/gulp
gulp.task('clinic', function (cb) {
return taskBuildClinic(gulp, env);
});
gulp.task('company', function (cb) {
return taskBuildCompany(gulp, env);
});
gulp.task('panel', function (cb) {
return taskBuildPanel(gulp, env);
});
In each build.js located in different app, it had:
var concat = require('gulp-concat');
var replace = require('gulp-replace');
...
if (env['production']) {
// replace something not for production
endpoint = "var EndpointBaseUrl = " + env['production']['EndpointBaseUrl'];
templateBaseUrl = "var TemplateBaseUrl = " + env['production']['TemplateBaseUrl'];
console.log(endpoint);
console.log(templateBaseUrl);
} else {
endpoint = "var EndpointBaseUrl = " + env['dev']['EndpointBaseUrl'];
templateBaseUrl = "var TemplateBaseUrl = " + env['dev']['TemplateBaseUrl'];
console.log(endpoint);
}
return gulp.src(files)
.pipe(concat(prefix + '.js'))
.pipe(replace(/var EndpointBaseUrl.*?;/g, endpoint))
.pipe(replace(/var TemplateBaseUrl.*?;/g, templateBaseUrl))
.pipe(gulp.dest('./build'));
In the app, I had:
var TemplateBaseUrl = "";
var EndpointBaseUrl = "";
Their content will be replaced by the value from gulp task.

page views functionality in angular js

i have setup mean js on my system. all crud operations work fine. my only issue that i cannot get around is to save pageviews when a user visits a page.
when a user visits a webpage like /articles/:articleId , how to increment the counter of page views for that page
here is my simple view function
$scope.findOne = function () {
$scope.article = Articles.get({
articleId: $stateParams.articleId
});
};
You would need to have a page views field in your mongoose model:
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Article Schema
*/
var ArticleSchema = new Schema({
pageViews: {
type: Number,
default: 0
},
// other fields
Then add a viewCounter() function to your 'ArticlesController' that increments the $scope.article.pageViews property and updates the article.
var viewCounter = function () {
//increment the page views
$scope.article.pageViews ++
// update the article record
$scope.article.$update(function(){
//handle success
}, function(err) {
//handle err
})
}
//call immediately
viewCounter();

Using Express to render an .ejs template for AngularJS and use the data inside AngularJS $scope

I hope I can explain myself with this first question I post on Stack Overflow.
I am building a small test application with the MEAN stack.
The application receives variable data from Mongoose based on an Express Route I have created.
For example the url is: localhost:3000/cities/test/Paris
Based on the name of the city the response gives me the name of the city and a description. I Know how to get this data inside the .ejs template
But thats not what I want. I want to use this data inside an ngRepeat.
Maybe this is not the right way but maybe you can help me figure this out.
The reason I want to do this is because I don't want a single page application but an Angular template that can be used over and over for each city and only uses the data that gets back from the mongoose find() results and not the whole cities array.
app.js :
var cityRoutes = require('./routes/cities');
app.use('/cities', cityRoutes);
app.set('views', './views'); // specify the views directory
app.set('view engine', 'ejs'); // register the template engine
./routes/cities/cities.js :
var express = require('express');
var citiesList = require('../server/controllers/cities-controller');
var bodyParser = require('body-parser');
var urlencode = bodyParser.urlencoded({ extended: false });
var router = express.Router();
// because this file is a fallback for the route /cities inside app.js
// the route will become localhost:3000/cities/test/:name
// not to be confused by its name in this file.
router.route('/test/:name')
.get(citiesList.viewTest)
module.exports = router;
../server/controllers/cities-controller.js :
var City = require('../models/cities');
module.exports.viewTest = function(request, responce){
City.find({ stad: request.params.name }, function(err, results){
if (err) return console.error(err);
if (!results.length) {
responce.json( "404" );
} else {
responce.render('angular.ejs', { messages:results });
// through this point everything works fine
// the angular.ejs template gets rendered correctly
// Now my problem is how tho get the results from the
// response.render inside the Angular directive
// so I can use the data in a $scope
}
});
};
../models/cities.js
var mongoose = require('mongoose');
module.exports = mongoose.model('City', {
stad: { type: String, required: true },
omschrijving: String
});
AngularJS directive :
// This is where I would like to use the messages result data
// so I can create a $scope that handles data that can be different
// for each url
// so basically I am using this directive as a template
app.directive('bestelFormulier', function () {
return {
restrict: 'E',
templateUrl: '/partials/bestel-formulier.html',
controller: ['$scope', '$http', '$resource', '$cookieStore',
function($scope, $http, $resource, $cookieStore){
// at this point it would be nice that the $scope gets the
// url based results. But I don't now how to do that..
// at this point the var "Cities" gets the REST API with
// all the cities...
var Cities = $resource('/cities');
// get cities from mongodb
Cities.query(function(results){
$scope.cities = results;
//console.log($scope.products);
});
$scope.cities = {};
}],
controllerAs: 'productsCtrl'
}
});
The database is stored like this :
[
{
stad: 'Paris',
omschrijving: 'description Paris',
},
{
stad: 'Amsterdam',
omschrijving: 'description Amsterdam',
}
]
I hope these files included helps explaining my issue.
Thanks in advance for helping me out
I figured out a way to do it...
The following changes to my code fixed my issue.
in app.js
var cityRoutes = require('./routes/cities');
app.use('/', cityRoutes);
// removed the name cities
./routes/cities/cities.js :
router.route('/cities/test/:name')
.get(citiesList.viewTest)
// added this route to use as an API
router.route('/api/cities/test/:name')
.get(citiesList.viewStad)
../server/controllers/cities-controller.js :
// added this callback so that a request to this url
// only responses with the data I need
module.exports.viewStad = function(request, responce){
City.find({ stad: request.params.name }, function(err, results){
if (err) return console.error(err);
if (!results.length) {
responce.json( "404" );
} else {
responce.json( results );
}
});
};
in my AngularJS app I added the $locationDirective and changed the following in my Angular directive to :
var url = $location.url();
var Cities = $resource('/api' + url);
// now when my .ejs template gets loaded the Angular part looks at
// the current url puts /api in front of it and uses it to get the
// correct resource
That is the way how I can use it in my $scope and use al the lovely Angular functionality :-)
Hope I can help other people with this... Eventually it was a simple solution and maybe there are people out there knowing beter ways to do it. For me it works now.

Strange behaviour of this in backbone.js Controller

Yes I am new to JS and also in backbonejs.
Lets dig into the problem now.
I am having a very strange behaviour of this in backbonejs Controller.
Here is the code of my controller
var controller = Backbone.Controller.extend( {
_index: null,
routes: {
"": "index"
},
initialize: function(options){
var self = this;
if (this._index === null){
$.getJSON('data/album1.json',function(data) {
//this line is working self._index is being set
self._index = new sphinx.views.IndexView({model: self._photos});
});
Backbone.history.loadUrl();
}
},
index: function() {
//this line is not working
//here THIS is pointing to a different object
//rather than it was available through THIS in initialize method
this._index.render();
}
});
Here is the lines at the end of the file to initiate controller.
removeFallbacks();
gallery = new controller;
Backbone.history.start();
Now , i am missing something. But what ???
If this is the wrong way what is the right way??
I need to access the properties i set from the initialize method from index method.
It looks like the caller function of index method is changing it's scope.
I need to preserve the scope of that.
You have to specify the route action into a Backbone Route not into a Controller. Inside the router is where you are going to initialize your controller and views.
Also, there is no method Backbone.history.loadURL(). I think you should use instead Backbone.history.start() and then call the navigate in the router instance e.g. router.navigate('state or URL');
var myApp = Backbone.Router.extend( {
_index: null,
routes: {
"": "index"
},
initialize: function(options){
//Initialize your app here
this.myApp = new myApp();
//Initialize your views here
this.myAppViews = new myAppView(/* args */);
var self = this;
if (this._index === null){
$.getJSON('data/album1.json',function(data) {
//this line is working self._index is being set
self._index = new sphinx.views.IndexView({model: self._photos});
});
Backbone.history.loadUrl(); //Change this to Backbone.history.start();
}
},
// Route actions
index: function() {
this._index.render();
}
});

Resources