Authentication is not checked in my angular app. User should not have access to "car" & "profile" views without login but now i can get to it. I've added "secure" property to the pages that should be hidden from non-authenticated user. I've added check for apprun in app.js. But it does not work.
here's services.js
'use strict';
angular.module('myApp')
.service('carsSrv', function () {
var carList = [];
var addUserCar = function (currObj, title, color, description, image) {
currObj = {
title: title,
color: color,
descriptiopn: description,
image: image
};
/* console.log("Car Added: " + currObj.id + "\n" + currObj.title + "\n" + currObj.color + "\n" + currObj.description + "\n" + currObj.image);*/
carList.push(currObj);
console.log(carList);
};
var getCars = function () {
console.log("User cars");
console.log(carList);
return carList;
};
return {
addUserCar: addUserCar,
getCars: getCars
}
})
.service('userSrv', userSrv)
.provider('storageSrv',storageSrv);
function userSrv(storageSrv, carsSrv) {
var user = {name: '', cars: carsSrv.carList };
this.getUser = function() {
return user;
};
this.getUserName = function () {
return user.name;
};
this.login = function(){
user.name = 'test name';
user.cars = init();
storageSrv.updateData(user);
return true;
}
this.logout = function(){
user.name = '';
user.cars = [];
alert('User logs out');
storageSrv.updateData(user);
}
this.checkLoginUser = function(){
return user.name !='';
}
this.getUserFeatures = function(){
return user.features;
}
this.registration = function(){
user.name = name;
user.cars = init();
}
function init(){
return storageSrv.getData();
}
}
function storageSrv(){
var storageName = 'cars';
return {
configStorageName : configStorageName,
$get:$get
};
function configStorageName(name){
if(name){
storageName = name;
return this;
}
else{
return storageName;
}
}
function $get(){
function updateStorage(data){
localStorage.setItem(storageName, data);
}
function getStorage(){
return localStorage.getItem(storageName);
}
function updateData(data){
console.log('storageName ' + storageName);
updateStorage(JSON.stringify(data));
}
function getData(){
console.log('storageName ' + storageName);
var data = getStorage();
return JSON.parse(data) || [];
}
return {
updateData: updateData,
getData:getData
}
}
};
and here's app.js
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute'
])
.constant('STORAGE_NAME', 'USER_CARS')
.config(configStorage)
.config(configRoutes)
.controller('carsCtrl', ['$scope', '$http', 'carsSrv',
function($scope, $http, carsSrv) {
$scope.view = "Cars";
$http.get('cars/cars.json')
.success(function(data) {
$scope.cars = data;
$scope.addCar = function(id, title, color, description, image) {
carsSrv.addUserCar(id, title, color, description, image);
};
})
.error(function() {
alert("can not get data from cars.json");
});
}
])
.controller('homeCtrl', ['$scope',
function($scope) {
$scope.view = "Home";
}
])
.controller('loginCtrl', ['userSrv', '$scope',
function(userSrv, $scope) {
$scope.view = "Login";
$scope.userLogin = function() {
userSrv.login();
}
$scope.userLogout = function() {
userSrv.logout();
}
}
])
.controller('profileCtrl', ['$scope', 'carsSrv',
function($scope, carsSrv) {
$scope.view = "Profile";
$scope.userCars = carsSrv.getCars();
}
]);
function configStorage(storageSrvProvider, STORAGE_NAME) {
console.log(storageSrvProvider);
storageSrvProvider.configStorageName(STORAGE_NAME);
}
function configRoutes($routeProvider) {
$routeProvider
.when('/cars', {
templateUrl: 'views/cars.html',
controller: 'carsCtrl',
secure: true
})
.when('/profile', {
templateUrl: 'views/profile.html',
controller: 'profileCtrl',
secure: true
})
.when('/home', {
templateUrl: 'views/home.html',
controller: 'homeCtrl',
secure: false
})
.when('/login', {
templateUrl: 'views/login.html',
controller: 'loginCtrl',
secure: false
})
.otherwise({
redirectTo: '/home'
});
}
var appRun = function($rootScope, $location, $userSrv) {
$rootScope.on('$routeChangeStart', function(event, next) {
if (next.secure && !userSrv.checkLoginUser()) {
$location.path('/login');
}
});
};
Your not really running the code appRun. Try adding this last line to your module declaration:
angular.module('myApp', [
'ngRoute'
])
.constant('STORAGE_NAME', 'USER_CARS')
.config(configStorage)
.config(configRoutes)
.run(appRun);
Also, because appRun is a variable containing an anonymous function, and not a function named appRun, by the time you call the run(appRun) (at the beginning of the file) the variable is defined but still undefined. That is why the function is not running.
Also, when listening to the event, you're using a function $rootScope.on(), instead of the correct name $rootScope.$on(). Apart from that, I tested it on my computed and it seems to be working.
function checkRoute ( userSrv, $location, current ) {
if (current.secure && !userSrv.checkLoginUser()) {
$location.path('/login');
}
}
function appRun ($rootScope, $route, $location, userSrv) {
$rootScope.$on('$routeChangeStart', function(event, next) {
checkRoute(userSrv, $location, next);
});
$rootScope.$on('sessionLogout', function () {
checkRoute(userSrv, $location, $route.current);
});
};
Update: For the logout to work, one strategy is to emit an event when logging out and then listen for that even and do the same check to see if the page is secure or not.
function userSrv($rootScope, storageSrv, carsSrv) {
//...
this.logout = function(){
user.name = '';
user.cars = [];
alert('User logs out');
storageSrv.updateData(user);
// Emit an event notifying the application that
// the user has logged out
$rootScope.$emit('sessionLogout');
}
//...
}
Related
I have an AngularJS module with code that calls a modal popup. I also have code that calls an MVC Web API controller method. Both of these functions work independently of one another right now. What I would like to happen is after the user clicks the OK button on the modal, I want to get the value of the modal text box and send it to the API controller as a parameter. The code I have so far is below:
app.js:
(function () {
'use strict';
var app = angular.module("CRNApp", ['ui.bootstrap','trNgGrid']);
var MainController = function ($scope, $http, $log, $uibModal) {
$scope.showGrid = false;
$scope.showPolicyScreen = false;
$scope.CRNViewModel = {
policyId: 0
};
$scope.openPolicyId = function () {
$uibModal.open({
templateUrl: 'templates/popupGetPolicy.cshtml',
backdrop: false,
windowClass: 'modal',
controller: function ($scope, $uibModalInstance, $log, CRNViewModel) {
$scope.CRNViewModel = CRNViewModel;
$scope.submit = function () {
}
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
},
resolve: { CRNViewModel: function () { return $scope.CRNViewModel; } }
});//end of modal.open
}; // end of scope.open fu
$scope.policyLookup = function (policyNumber) {
$scope.loading = true;
$scope.CRNViewModel.policyId = policyNumber; //"WCZ25999"
$http.post("/api/Policy"
, $scope.CRNViewModel
, { header: { 'Content-Type': 'application/json' } })
.then(function (response) {
$scope.policy = response.data;
$scope.loading = false;
$scope.showGrid = false;
$scope.showPolicyScreen = true;
})
.catch(function (error) {
console.log(error);
$scope.loading = false;
$scope.showGrid = false;
});
};
};
app.controller("MainController", MainController);
}());
The MVC API Controller method:
// POST: api/Policy
public IHttpActionResult Post([FromBody]CRNViewModel policy)
{
CRNViewModel _crnVM = new CRNViewModel();
IConditionalRenewalNotices _crn = new ConditionalRenewalNoticesRepository();
_crnVM = _crn.GetPolicyByPolicyId(policy.PolicyId);
return Json(_crnVM);
}
Return the textbox value when you close the $uibModalInstance instance and then add a callback for the modal result:
var modal = $uibModal.open({
templateUrl: 'templates/popupGetPolicy.cshtml',
backdrop: false,
windowClass: 'modal',
controller: function($scope, $uibModalInstance, $log, CRNViewModel) {
$scope.CRNViewModel = CRNViewModel;
$scope.submit = function () {
// pass in the value you want to return
$uibModalInstance.close('WCZ25999');
}
$scope.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
},
resolve: { CRNViewModel: function() { return $scope.CRNViewModel; } }
});
modal.result.then(function (value) {
$scope.policyLookup(value);
});
just starting out really with Angular and need some advice regarding preventing repeated ajax requests for the same data when re-using a controller with multiple view.
So I have say 6 views all referencing the same controller but different views
app.js
(function() {
var app = angular.module('myApp', ['ngRoute','ui.unique']);
app.config(function ($routeProvider) {
// Routes
$routeProvider
.when('/',
{
controller: 'SamplesController',
templateUrl: 'app/views/home.html'
})
.when('/view2/',
{
controller: 'SamplesController',
templateUrl: 'app/views/main.html'
})
.when('/view3/:rangeName',
{
controller: 'SamplesController',
templateUrl: 'app/views/samples.html'
})
.when('/view4/:rangeName',
{
controller: 'SamplesController',
templateUrl: 'app/views/samples.html'
})
.when('/view5/',
{
controller: 'SamplesController',
templateUrl: 'app/views/basket.html'
})
.when('/view6/',
{
controller: 'SamplesController',
templateUrl: 'app/views/lightbox.html'
})
.otherwise({ redirectTo: '/' });
});
}());
samplesController.js
(function() {
var SamplesController = function ($scope, SamplesFactory, appSettings, $routeParams) {
function init() {
// back function
$scope.$back = function() {
window.history.back();
};
// app settings
$scope.settings = appSettings;
// samples list
SamplesFactory.getSamples()
.success(function(data){
var returnSamples = [];
for (var i=0,len=data.length;i<len;i++) {
if (data[i].range === $routeParams.rangeName) {
returnSamples.push(data[i]);
}
}
$scope.samples = returnSamples;
})
.error(function(data, status, headers, config){
// return empty object
return {};
});
// variables for both ranges
$scope.rangeName = $routeParams.rangeName;
// click to change type
$scope.populate = function(type) {
$scope.attributeValue = type;
};
};
init();
};
SamplesController.$inject = ['$scope','SamplesFactory', 'appSettings', '$routeParams'];
angular.module('myApp').controller('SamplesController', SamplesController);
}());
samplesFactory.js
(function () {
var SamplesFactory = function ($http) {
var factory = {};
factory.getSamples = function() {
return $http.jsonp('http://www.website.com/app/index.php?callback=JSON_CALLBACK');
};
return factory;
};
SamplesFactory.$inject = ['$http'];
angular.module('myApp').factory('SamplesFactory', SamplesFactory);
}());
So with this - every time a new view is loaded the ajax request is made again - how would I re-purpose to have only a single request happen?
As always thanks in advance
Carl
UPDATE: Answer marked below but I also had success by changing the "cache" config item/property (whatever its called) to true in the jsonp request
return $http.jsonp('http://www.website.com/app/index.php?callback=JSON_CALLBACK',{cache: true});
You could change your factory in this way:
(function () {
var SamplesFactory = function ($http) {
var factory = {},
samples = $http.jsonp('http://www.website.com/app/index.php?callback=JSON_CALLBACK');
factory.getSamples = function() {
return samples;
};
return factory;
};
SamplesFactory.$inject = ['$http'];
angular.module('myApp').factory('SamplesFactory', SamplesFactory);
}());
Now getSamples() returns a promise that you should manage in your controllers.
I am using angular-foundation and specifically the modal http://madmimi.github.io/angular-foundation/#/modal , i am confused in how to pass data to a modal while using one controller , i want to take an array value and update the modal to show a particular user info ,Ex: $scope.updateUserInfo = $scope.user[index] , the only issue is how to pass the data to the modal .
myApp.controller('users',function ($scope,$location,$http,$modal,msg) {
$http.get('api/v1/users')
.success(function (data,status) {
$scope.user = data;
})
.error(function (data,status) {
$location.path('/login');
});
$scope.showWrite = function () {
$scope.write = true;
}
$scope.closeWrite = function () {
$scope.write = false;
$scope.newUser = '';
}
$scope.save = function () {
$http.post('api/v1/users/store',$scope.newUser)
.success(function (data,status) {
$scope.user.unshift({
id: data,
first_name: $scope.newUser.first_name,
last_name: $scope.newUser.last_name,
email: $scope.newUser.email,
role: $scope.newUser.role
});
$scope.write = false;
$scope.newUser = '';
})
.error(function (data,status) {
alert('failed');
});
}
$scope.confirmDelete = function (index,id) {
msg.confirmDelete().then(function(value) {
$scope.text = msg.getText();
$http.get('api/v1/users/destroy/'+id)
.success(function (data,status) {
$scope.user.splice(index,1);
})
.error(function (data,status) {
alert('Error : Operation failed');
});
});
}
$scope.showUserInfo = function () {
}
$scope.userUpdate = function () {
}
$scope.showUserUpdate = function (index) {
$modal.open({
templateUrl: 'partials/message/update.html',
controller: 'users'
});
}
});
To Pass the data to $modal you need to update your $modal function something like this:
$scope.showUserUpdate = function (popUpData) {
var modalInstance = $modal.open({
templateUrl: 'partials/message/update.html',
controller: ['$scope', '$rootScope', '$modalInstance',
function($scope, $rootScope, $modalInstance) {
$scope = angular.extend($scope, popUpData);
}],
resolve: {}
});
return modalInstance;
};
So popupData is the data which you want to pass to your modal. popupdata then will be merged with existing scope of that controller. Now you can access popupData keys in your HTML. Remember we are returning modal instance in this function so you can manually close the popup using this intance.
Other way is to use the resolve attribute and inject it to controller:
$scope.showUserUpdate = function (popUpData) {
var modalInstance = $modal.open({
templateUrl: 'partials/message/update.html',
controller: ['$modalInstance', 'data', function($modalInstance, data) {
data.popUpData = ...
}],
resolve: {
data: popUpData
}
});
return modalInstance;
};
I'm trying to learn angular by extending a sample app to use firebase. I want to modify the service object being used to call firebase instead of my webserver. I tried to inject $scope into my service object and am now getting an error. What am I doing wrong?
var app = angular.module("myApp", ['ngRoute', 'firebase']);
app.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: "templates/home.html",
controller: "HomeController"
})
.when('/settings', {
templateUrl: 'templates/settings.html',
controller: 'SettingsController'
})
.otherwise({ redirectTo: '/' });
});
//services must return objects
app.service('mailService', ['$scope', '$http', '$firebase', function($scope, $http, $firebase) {
var mailRef = new Firebase("https://ng-book-email-client.firebaseio.com/mail");
//var getMail = function() {
// return $http({
// method: 'GET',
// url: '/api/mail'
// });
//};
$scope.email = $firebase(mailRef);
var sendEmail = function(mail) {
//var d = $q.defer();
//$http({
// method: 'POST',
// data: 'mail',
// url: '/api/send'
//}).success(function(data, status, headers) {
// d.resolve(data);
//}).error(function(data, status, headers) {
// d.reject(data);
//});
//return d.promise;
return $scope.email.$add(mail);
};
return {
//getMail: getMail,
sendEmail: sendEmail
};
}]);
app.controller('HomeController', function($scope) {
$scope.selectedMail;
$scope.setSelectedMail = function(mail) {
$scope.selectedMail = mail;
};
$scope.isSelected = function(mail) {
if($scope.selectedMail) {
return $scope.selectedMail === mail;
}
};
});
// directive that builds the email listing
app.directive('emailListing', function() {
var url = "http://www.gravatar.com/avatar/";
return {
restrict: 'EA', // E- element A- attribute C- class M- comment
replace: false, // whether angular should replace the element or append
scope: { // may be true/false or hash. if a hash we create an 'isolate' scope
email: '=', // accept an object as parameter
action: '&', // accept a function as a parameter
isSelected: '&',
shouldUseGravatar: '#', // accept a string as a parameter
gravatarSize: '#'
},
transclude: false,
templateUrl: '/templates/emailListing.html',
controller: ['$scope', '$element', '$attrs', '$transclude',
function($scope, $element, $attrs, $transclude) {
$scope.handleClick = function() {
$scope.action({selectedMail: $scope.email});
};
}
],
// if you had a compile section here, link: wont run
link: function(scope, iElement, iAttrs, controller) {
var size = iAttrs.gravatarSize || 80;
scope.$watch('gravatarImage', function() {
var hash = md5(scope.email.from[0]);
scope.gravatarImage = url + hash + '?s=' + size;
});
iElement.bind('click', function() {
iElement.parent().children().removeClass('selected');
iElement.addClass('selected');
});
}
};
});
app.controller('MailListingController', ['$scope', 'mailService', function($scope, mailService) {
$scope.email = [];
$scope.nYearsAgo = 10;
//mailService.getMail()
//.success(function(data, status, headers) {
// $scope.email = data.all;
//})
//.error(function(data, status, headers) {
//});
$scope.searchPastNYears = function(email) {
var emailSentAtDate = new Date(email.sent_at),
nYearsAgoDate = new Date();
nYearsAgoDate.setFullYear(nYearsAgoDate.getFullYear() - $scope.nYearsAgo);
return emailSentAtDate > nYearsAgoDate;
};
}]);
app.controller('ContentController', ['$scope', 'mailService', '$rootScope', function($scope, mailService, $rootScope) {
$scope.showingReply = false;
$scope.reply = {};
$scope.toggleReplyForm = function() {
$scope.reply = {}; //reset variable
$scope.showingReply = !$scope.showingReply;
console.log($scope.selectedMail.from);
$scope.reply.to = $scope.selectedMail.from.join(", ");
$scope.reply.body = "\n\n -----------------\n\n" + $scope.selectedMail.body;
};
$scope.sendReply = function() {
$scope.showingReply = false;
$rootScope.loading = true;
mailService.sendEmail($scope.reply)
.then(function(status) {
$rootScope.loading = false;
}, function(err) {
$rootScope.loading = false;
});
}
$scope.$watch('selectedMail', function(evt) {
$scope.showingReply = false;
$scope.reply = {};
});
}]);
app.controller('SettingsController', function($scope) {
$scope.settings = {
name: 'harry',
email: "me#me.com"
};
$scope.updateSettings = function() {
console.log("updateSettings clicked")
};
});
error
Error: [$injector:unpr] http://errors.angularjs.org/1.2.14/$injector/unpr?p0=<div ng-view="" class="ng-scope">copeProvider%20%3C-%20%24scope%20%3C-%20mailService
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js:6:450
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js:32:125
at Object.c [as get] (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js:30:200)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js:32:193
at c (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js:30:200)
at d (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js:30:417)
at Object.instantiate (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js:31:80)
at Object.<anonymous> (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js:31:343)
at Object.d [as invoke] (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js:30:452) angular.js:9509
The answer is that the $scope shouldn't be injected into services or factories. They're supposed to be reusable and sharable. The right way to achieve the effect is to create a $firebase object inside the service and return a function that can take any variable and scope and $bind them to the firebase object.
Inspiration comes from http://plnkr.co/edit/Uf2fB0?p=info
var app = angular.module("myApp", ['ngRoute', 'firebase']);
//services must return objects
app.service('mailService', ['$http', '$firebase', function($http, $firebase) {
var emailRef = new Firebase("https://ng-book-email-client.firebaseio.com/all");
var emails = $firebase(emailRef);
// uses firebase to bind $scope.email to the firebase mail object
var setEmails = function(scope, localScopeVarName) {
return emails.$bind(scope, localScopeVarName);
};
var sendEmail = function(mail) {
return $scope.email.$add(mail);
};
return {
setEmails: setEmails,
sendEmail: sendEmail
};
}]);
app.controller('MailListingController', ['$scope', 'mailService', function($scope, mailService) {
mailService.setEmails($scope, 'emails');
$scope.nYearsAgo = 10;
$scope.searchPastNYears = function(email) {
var emailSentAtDate = new Date(email.sent_at),
nYearsAgoDate = new Date();
nYearsAgoDate.setFullYear(nYearsAgoDate.getFullYear() - $scope.nYearsAgo);
return emailSentAtDate > nYearsAgoDate;
};
}]);
I think you should not inject $scope to a service, Service can be a common one for implementation /support for several controllers and service shouldn't know about a $scope (controller). But controllers users services to make their work done by passing parameters to a service method.
mailService.sendEmail($scope.reply)
Not sure why you need $scope inside a service here,
$scope.email = $firebase(mailRef);
are you expecting something like this,
this.email = $firebase(mailRef);
I have an ng-click calling $scope.get_post_Range which is to return a range of database queries. The problem is that after it is completed, My original controller main function runs again ('post_View_Ctrl'). This returns the entire database collection. How do i stop this? The strange thing is that if I click the link again, it runs the function and not the original main controller.
var blogAppViewController = angular.module ('blogAppViewController', []);
blogAppViewController.controller('post_View_Ctrl', function ($scope, $http, $routeParams, $location) {
$scope._idList=[];
var globalPAGECount=0;
$http.get('/allposts').success(function(input_data) {
$scope.posts = input_data;
var posts_Length=$scope.posts.length;
$scope.post1=input_data[0];
$scope.post2=input_data[1];
$scope.post3=input_data[2];
$scope.post4=input_data[3];
$scope.post5=input_data[4];
$scope._idList.push({"Page":1, "_id":$scope.posts[0]._id});
var count=0;
var PageCount=2;
for (var each in $scope.posts){
count++;
if (count==5){
$scope._idList.push({"Page": PageCount, "_id": $scope.posts[each]._id});
count=0;
PageCount++;
}
}
$scope._idList.push({"Page": PageCount, "_id":$scope.posts[posts_Length-1]._id});
var listLength = $scope._idList.length;
// console.log($scope._idList[listLength-1]);
if($scope._idList[listLength-1]._id == $scope._idList[listLength-2]._id ){
$scope._idList.pop();
}
console.log($scope._idList);
$scope.a=globalPAGECount+1;
$scope.a_id=$scope._idList[globalPAGECount]['_id'];
$scope.b=globalPAGECount+2;
$scope.b_id=$scope._idList[globalPAGECount+1]['_id'];
$scope.c=globalPAGECount+3;
$scope.c_id=$scope._idList[globalPAGECount+2]['_id'];
$scope.d=globalPAGECount+4;
$scope.d_id=$scope._idList[globalPAGECount+3]['_id'];
$scope.e=globalPAGECount+5;
$scope.e_id=$scope._idList[globalPAGECount+4]['_id'];
});
$scope.get_post_Range = function(high,low) {
console.log(high, low);
console.log("At least enters here");
$http.get('/get_posts/high/' + high + '/low/' + low).success(function (returned) {
$scope.posts = returned;
console.log("success");
});
};
$scope.selectSearch = function(input) {
$scope.Search1 = input;
if ($scope.Search1 == 'Title'){
$scope.searchTitle = true;
$scope.searchContent = false;
$scope.search_Hits=null;
}
if ($scope.Search1 == 'Post Content'){
$scope.searchTitle = false;
$scope.searchContent = true;
$scope.search_Hits=null;
}
};
$scope.searchDatabase = function(type, input) {
if (type === 'Title') {
$http.post('/search_post_Titles', {title: input}).success(function (response) {
$scope.search_Hits = response;
});
}
if (type === 'Post Content') {
$http.post('/search_post_Content', {post: input}).success( function (response) {
$scope.search_Hits = response;
});
}
};
});
///////////
///////////
var blogApp = angular.module('blogApp', [
'ngRoute',
'ngResource',
'blogAppViewController',
'blogSingleViewController',
'blognewEntryController',
]);
blogApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/' , {
templateUrl: 'partials/all-posts.html',
controller: 'post_View_Ctrl'
}).
when('/post/:title' , {
templateUrl: 'partials/single-post.html',
controller: 'single_View_Ctrl'
}).
when('/get_posts/high/:high/low/:low' , {
templateUrl: 'partials/all-posts.html',
controller: 'post_View_Ctrl'
}).
when('/new_entry' , {
templateUrl: 'partials/new_Entry.html',
controller: 'entry_View_Ctrl'
}).
otherwise({
redirectTo: '/'
});
}]);
Controllers are design to execute only once per navigation change so there is no obvious reason to execute twice here.
Maybe you are declaring the controller both at $routeProvider level (as you shown) and at html level (see this question)
If it didn't solve the problem, a plunker will be needed here.