Passing variables betweencontrollers in angular js - javascript

I am new to angular js and its services so please bear with this basic question. Please read comment inside code to understand what I need.
.controller('ctrlr1', function($scope, myservice) {
var a = "abc";
})
.controller('ctrl2', function ($scope, myservice) {
// how to get value of a
})
.service('myservice', function() {
//what goes here?
});
Thanks in advance

Basic sharing by angular services
.controller('ctrlr1', function($scope, myservice) {
var a = "abc";
var b = 123;
myservice.myData = a;
myservice.myDataB = b;
})
.controller('ctrl2', function ($scope, myservice) {
// how to get value of a
console.log(myservice.myData);
console.log(myservice.myDataB);
})
.service('myservice', function() {
//what goes here?
this.myData = '';
this.myDataB = 0;
});

You can use myservice because its the efficient way but don't use $brodcast.
Here is an example:-
var testModule = angular.module('testmodule', []);
testModule
.controller('QuestionsStatusController1',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
testModule
.controller('QuestionsStatusController2',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
testModule
.service('myservice', function() {
this.xxx = "yyy";
});

Related

TypeError: Cannot read property 'go' of undefined in AngularJS

I am creating an web app, when splicing an object in a array. All of sudden, I am getting this error in the console that says: TypeError: Cannot read property 'go' of undefined.
Here is my code:
var app = angular.module("Portal", ['ngRoute', 'ui.bootstrap' ]);
app.controller('MainCtrl', MainCtrl);
$scope.inactive = true;
MainCtrl.$inject = ['$scope', '$window', '$timeout', '$state'];
function MainCtrl($scope, $window, $timeout, $state) {
$scope.deleteAction = function (people) {
$timeout(function () {
var index = $scope.userInfo.persons.indexOf(people);
console.log($scope.userInfo.persons);
$scope.userInfo.persons.splice(index, 1);
console.log($scope.userInfo.persons);
$state.go($state.current, {}, {reload: true});
$window.location.href = '#/person';
}, 100);
};
}
It seems that you are not injecting $state service. Notice the last parameter in your controller definition:
app.controller('MainCtrl', function($scope, $window, $timeout, $state) {
$scope.deleteAction = function (people) {
$timeout(function () {
var index = $scope.userInfo.persons.indexOf(people);
console.log($scope.userInfo.persons);
$scope.userInfo.persons.splice(index, 1);
console.log($scope.userInfo.persons);
$state.go($state.current, {}, {reload: true});
$window.location.href = '#/person';
}, 100);
};
});
Here is a recomended version of the controller definition, that plays nicely with code uglifiers:
app.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope', '$window', '$timeout', '$state'];
function MainCtrl($scope, $window, $timeout, $state) {
$scope.deleteAction = function (people) {
$timeout(function () {
var index = $scope.userInfo.persons.indexOf(people);
console.log($scope.userInfo.persons);
$scope.userInfo.persons.splice(index, 1);
console.log($scope.userInfo.persons);
$state.go($state.current, {}, {reload: true});
$window.location.href = '#/person';
}, 100);
};
});

Cannot read propery getRiders of undefined

I want to call a service which I defined in DeliverService but when I called it from controller it gives an error of Cannot read propery getRiders of undefined , NO idea why this happened :|
DeliverService.js
angular.module('Deliver')
.service('DeliverService', ['$http', '$state', '$resource', '$q', 'SettingService', '$localStorage', "MessageService", function($http, $state, $resource, $q, SettingService, $localStorage, MessageService) {
var service = {
getRiders : function(){
return $http.get("Hero.json");
//return $http.get(SettingService.baseUrl + "api/orders");
} }
return service;
}]);
DeliverCtrl.js
use strict';
angular.module('Deliver').controller('DeliverCtrl',['$scope','$state', "SettingService","DeliverService", function($scope, $state, $ionicModal, MessageService, SettingService,DeliverService) {
$scope.riders = [];
DeliverService.getRiders().then(function(response){
$scope.riders = response.data.data;
}, function(error){
});
}]);
Your dependencies aren't in the matching order here. Hence, DeliverService isn't actually injected.
Your controller code should look something like this:
angular.module('Deliver').controller('DeliverCtrl',
['$scope','$state', '$ionicModal', 'MessageService', 'SettingService','DeliverService',
function($scope, $state, $ionicModal, MessageService, SettingService, DeliverService) {
$scope.riders = [];
DeliverService.getRiders().then(function(response){
$scope.riders = response.data.data;
}, function(error){});
}]);
In DeliverCtrl.js
The injection Parameter and function parameters do not match
It should be like this
['$scope','$state','$ionicModal','MessageService','SettingService','DeliverService', function($scope, $state, $ionicModal, MessageService, SettingService,DeliverService)

AngularJS: $routeParams to work within a service

I know this is easy, but I can't quite wrap my head around how to do this.
I need to do the API call within a service so that those variables can be accessed between two separate controllers.
The problem I am having is I can't access $routeParams (which I need for the get) within the service. I can't figure out know how to pass $routeParams from the controller to the service.
app.controller('Main', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
$scope.Page = Page;
}]);
app.controller('Pages', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
$scope.Page = Page.posts;
}]);
app.factory('Page', ['$routeParams', '$http', function($routeParams, $http) {
var posts = function posts() {
$http.get('wp-json/wp/v2/pages/?filter[name]='+ $routeParams.slug).success(function(res){
console.log(JSON.stringify(res) );
});
};
var description = '';
var title = '';
return {
title: function () { return title; },
setTitle: function (newTitle) { title = newTitle; },
description: function () { return description; },
setDescription: function (newDescription) { description = newDescription; },
posts
};
}]);
factory :
app.factory('Page', ['$http', function($http) {
var _posts = function posts(param) {
return $http.get('wp-json/wp/v2/pages/?filter[name]='+ param);
};
var description = '';
var title = '';
return {
title: function () { return title; },
setTitle: function (newTitle) { title = newTitle; },
description: function () { return description; },
setDescription: function (newDescription) { description = newDescription; },
posts : _posts
};
}]);
Controller :
app.controller('Pages', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
Page.posts($routeParams.slug).then(function success(response) {
$scope.Page = response.data;
}, function error(reason) {
// do something
});
}]);
please note that success is deprecated in newer versions of Angular. I have updated the code with then

AngularJS: '$scope is not defined'

I keep getting '$scope is not defined' console errors for this controller code in AngularJS:
angular.module('articles').controller('ArticlesController', ['$scope', '$routeParams', '$location', 'Authentication', 'Articles',
function($scope, $routeParams, $location, Authentication, Articles){
$scope.authentication = Authentication;
}
]);
$scope.create = function() { // THROWS ERROR ON THIS INSTANCE OF $SCOPE
var article = new Articles({
title: this.title,
content: this.content
});
article.$save(function(response) {
$location.path('articles/' + response._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
Where in my AngularJS MVC files should I be looking at to find problems with the $scope not being defined properly?
For others who land here from Google, you'll get this error if you forget the quotes around $scope when you're annotating the function for minification.
Error
app.controller('myCtrl', [$scope, function($scope) {
...
}]);
Happy Angular
app.controller('myCtrl', ['$scope', function($scope) {
...
}]);
Place that code inside controller:-
angular.module('articles').controller('ArticlesController', ['$scope', '$routeParams', '$location', 'Authentication', 'Articles',
function($scope, $routeParams, $location, Authentication, Articles){
$scope.authentication = Authentication;
$scope.create = function() { // THROWS ERROR ON THIS INSTANCE OF $SCOPE
var article = new Articles({
title: this.title,
content: this.content
});
article.$save(function(response) {
$location.path('articles/' + response._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
}
]);
Just put you $scope.create function inside your controller. Not outside !
$scope is only defined in controllers, each controller have its own. So write $scope outside your controller can't work.
Check scope variable declared after controller defined.
Eg:
var app = angular.module('myApp','');
app.controller('customersCtrl', function($scope, $http) {
//define scope variable here.
});
Check defined range of controller in view page.
Eg:
<div ng-controller="mycontroller">
//scope variable used inside these blocks
<div>

Learning Angular Seed Notation

I was following a question (ui bootstrap modal's controller 'is not defined'), which I then tried modifying for nested controllers, different scoping calls, and renaming/refactoring the code (for learning).
I couldn't get it working in My Plunker, so that leaves me with a few questions:
Why is it not working?
The original question shows creating a new module, rather than appending controllers to the app module -- why? Is this recommended?
If PageController is the ancestor controller, how would it's $scope.open method reference the other controllers open definition?
Code:
var app = angular.module('app', ['ui.bootstrap']);
app.controller('PageController', ['$scope',
function($scope) {
$scope.open = function() {
// how to call ModalController.open?
};
}
])
.controller('ModalController', ['$scope', '$modal', '$log',
function($scope, $modal, $log) {
$scope.items = ['item1', 'item2', 'item3'];
$scope.open = function() {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
resolve: {
items: function() {
return $scope.items;
}
}
});
modalInstance.result.then(function(selectedItem) {
$scope.selected = selectedItem;
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
}
])
.controller('ModalInstanceCtrl', ['$scope', '$modalInstance', 'items',
function($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function() {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
}
]);

Categories