$scope not getting defined properly - angularjs

I am trying to attach notes to $scope instead of controller(this) in the following code:
angular.module('NoteWrangler')
.controller('NotesIndexController', ['$http', function($http) {
var controller = this;
$http({method: 'GET', url: '/notes'}).success(function(data) {
controller.notes = data;
});
}]);
So, when I define $scope like the following :
.controller('NotesIndexController', ['$scope', function($scope)
It doesn't work as I would need to define $http somewhere in order to use it in the code? So, where exactly I should define $scope then?
I have referred this documentation.

You don't "define" $scope, it is a framework object that is managed for you.
If you use the ControllerAs Syntax, your controller can be added to $scope as a property. Otherwise, you would need to refer to the $scope object that is injectable through Angular Dependency Injection. You can inject as many dependencies as you need for your app.
So, the two options which you have available to you are:
ControllerAs:
angular.module('NoteWrangler')
.controller('NotesIndexController', ['$http', function($http) {
var controller = this;
$http({method: 'GET', url: '/notes'}).success(function(data) {
controller.notes = data;
});
}]);
<div ng-controller="NotesIndexController as controller">
{{controller.notes}}
</div>
Direct $scope:
angular.module('NoteWrangler')
.controller('NotesIndexController', ['$scope', '$http', function($scope, $http) {
var controller = this;
$http({method: 'GET', url: '/notes'}).success(function(data) {
$scope.notes = data;
});
}]);
<div ng-controller="NotesIndexController">
{{notes}}
</div>
Note that the $scope object is implicit in the first example and not required in the controller code, and explicit in the second. Also note, $scope has some specific rules regarding primitives and Prototype Inheritance, so it is always recommended to use a dot in your HTML bindings, which the ControllerAs syntax enforces automatically.
Ultimately, the choice of which syntax to use is up to you, but it's recommended to be consistent throughout your application, and either always reference $scope or only reference it for special properties you can't reach any other way.

angular
.module('NoteWrangler')
.controller('NotesIndexController', ['$scope', '$http', function($scope, $http) {
$http({method: 'GET', url: '/notes'}).success(function(data) {
$scope.notes = data;
});
}]);

Not sure why you are using var controller = this; but you have not injected $http
You can use it like
.controller('NotesIndexController', ['$scope', '$http', function($scope, $http){
$http({method: 'GET', url: '/notes'})
.success(function(data) {
$scope.notes = data;
});
}]);

Related

angular function call before html view is load

I am working on angularjs (1.6) and want to made a functionality in angular service, its call when a controller call and its service have an ajax code like
app.service('myServ', function($http, $window){
this.backdoor=function(){
$http({
method : 'get',
url : 'web_services/backdoor.php'
}).then(function(res){
// console.log(res.data);
// console.log(res.data.length);
if(res.data.length==0)
{
$window.location.href="index.html";
}
});
}});
and my controller code is :
app.controller('myCtrl', function($scope, $http, $window, myServ, $routeParams){
myServ.backdoor();
});
so the above code (service) is check a user session is created or not, but the problem is when session is not created on server side then my html page load for a second then server will call $window.location.href so please help me about the right way to do this....
I believe you need a resolve in angular.config. Its job is to run some code before you are being redirected to your route/state (for ngRoute or ui.router).
To do that you would need to have:
app.service('myServ', function($http, $window){
this.backdoor=function(){
return $http({ // return the promise if you need to use the values in the controller
method : 'get',
url : 'web_services/backdoor.php'
}).then(function(res){
if(res.data.length==0){ $window.location.href="index.html"; }
else{ return res.data; } // return the values
});
}});
and main part:
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/your_page/:route_params', {
templateUrl: 'your_page_partial.html',
controller: 'myCtrl',
resolve: {
resolvedVal: function resMyService(myServ, $routeParams){ // setting an injectable instance `resolvedVal`
/* use $routeParams values as parameters? */
return myServ.backdoor(); // calling your service
}
}}
);
}]);
Then it's enough to just inject your resolve into the controller:
app.controller('myCtrl', function($scope, $http, $window, resolvedVal){ // note: resolvedVal injection
$scope.my_data = resolvedVal;
});

undefined attribute in use of $controllerProvider in Angular

I'm a newbie in Angular, i whant to make use of $controllerProvider, i see an example like my code, but the attribute register got undefined:
var appTmw = angular.module('appTmw', ['ui.router']);
appTmw.config(function($stateProvider, $urlRouterProvider, $controllerProvider) {
appTmw.register = {
controller: $controllerProvider.register
};
})
and here, a register of controller, the register attribute got undefined:
appTmw.register.controller('CustomersController', ['$scope', 'config', 'dataService',
function ($scope, config, dataService) {
//Controller code goes here
}]);
what a problem with the code?
controllerProvider is the $controller service used by Angular to create new controllers:
https://docs.angularjs.org/api/ng/provider/$controllerProvider
If you are new to angular I suggest you to use the standard way to create a controller:
var appTmw = angular.module('appTmw', ['ui.router']);
appTmw.controller('controllerName', function($scope){
//your code for the controller here
});
I hope it helps.

Angular factory returning a promise

When my app starts I load some settings from a server. Most of my controllers need this before anything useful can be done. I want to simplify the controller's code as much as possible. My attempt, which doesn't work, is something like this:
app.factory('settings', ['$rootScope', '$http', '$q', function($rootScope, $http, $q) {
var deferred = $q.defer();
$http.get('/api/public/settings/get').success(function(data) {
$rootScope.settings = data;
deferred.resolve();
});
return deferred.promise;
}]);
app.controller('SomeCtrl', ['$rootScope', 'settings', function($rootScope, settings) {
// Here I want settings to be available
}]);
I would like to avoid having a lot of settings.then(function() ...) everywhere.
Any ideas on how to solve this in a nice way?
$http itself return promise you don't need to bind it inside the $q this is not a good practice and considered as Anti Pattern.
Use:-
app.factory('settings', ['$rootScope', '$http', '$q', function($rootScope, $http) {
return $http.get('/api/public/settings/get')
}]);
app.controller('SomeCtrl', ['settings',$scope, function(settings,$scope) {
settings.then(function(result){
$scope.settings=result.data;
});
}]);
Your way can be done as :-
app.factory('settings', ['$rootScope', '$http', '$q', function($rootScope, $http, $q) {
var deferred = $q.defer();
$http.get('/api/public/settings/get').success(function(data) {
deferred.resolve(data);
});
return deferred.promise;
}]);
app.controller('SomeCtrl', ['$scope', 'settings', function($scope, settings) {
settings.then(function(data){
$scope.settings=data;
})
}]);
Don't overload $rootScope if you wanted it you need to use $watch for the changes in $rootScope(Not recommended).
Somewhere you would need to "wait".
The only built-in way in Angular to completely absolve the controller from having to wait on its own for async data to be loaded is to instantiate a controller with $routeProvider's route's resolve property (or the alternative $stateProvider of ui.router). This will run controller only when all the promises are resolved, and the resolved data would be injected.
So, ng-route alternative - plunker:
$routeProvider.when("/", {
controller: "SomeCtrl",
templateUrl: "someTemplate.html",
resolve: {
settings: function(settingsSvc){
return settingsSvc.load(); // I renamed the loading function for clarity
}
});
Then, in SomeCtrl you can add settings as an injectable dependency:
.controller("SomeCtrl", function($scope, settings){
if (settings.foo) $scope.bar = "foo is on";
})
This will "wait" to load someTemplate in <div ng-view></div> until settings is resolved.
The settingsSvc should cache the promise so that it won't need to redo the HTTP request. Note, that as mentioned in another answer, there is no need for $q.defer when the API you are using (like $http) already returns a promise:
.factory("settingsSvc", function($http){
var svc = {settings: {}};
var promise = $http.get('/api/public/settings/get').success(function(data){
svc.settings = data; // optionally set the settings data here
});
svc.load = function(){
return promise;
}
return svc;
});
Another approach, if you don't like the ngRoute way, could be to have the settings service broadcast on $rootScope an event when settings were loaded, and controllers could react to it and do whatever. But that seems "heavier" than .then.
I guess the third way - plunker - would be to have an app-level controller "enabling" the rest of the app only when all the dependencies have preloaded:
.controller("AppCtrl", function($q, settingsSvc, someOtherService){
$scope.loaded = false;
$q.all([settingsSvc.load, someOtherService.prefetch]).then(function(){
$scope.loaded = true;
});
});
And in the View, toggle ng-if with loaded:
<body ng-controller="AppCtrl">
<div ng-if="!loaded">loading app...</div>
<div ng-if="loaded">
<div ng-controller="MainCtrl"></div>
<div ng-controller="MenuCtrl"></div>
</div>
</body>
Fo ui-router this is easily done with having an application root state with at least this minimum definition
$stateProvider
.state('app', {
abstract: true,
template: '<div ui-view></div>'
resolve: {
settings: function($http){
return $http.get('/api/public/settings/get')
.then(function(response) {return response.data});
}
}
})
After this you can make all application states inherit from this root state and
All controllers will be executed only after settings are loaded
All controllers will gain access to settings resolved value as possible injectable.
As mentioned above resolve also works for the original ng-route but since it does not support nesting the approach is not as useful as for ui-router.
You can manually bootstrap your application after settings are loaded.
var initInjector = angular.injector(["ng"]);
var $http = initInjector.get("$http");
var $rootScope = initInjector.get("$rootScope");
$http.get('/api/public/settings/get').success(function(data) {
$rootScope.settings = data;
angular.element(document).ready(function () {
angular.bootstrap(document, ["app"]);
});
});
In this case your whole application will run only after the settings are loaded.
See Angular bootstrap documentation for details

angularjs: design issue for module definition

I am so annoyed with AngularJS ! I've designed my modules using the following syntax:
angular.module('myModule.controllers').controller('someCtrl',
['$scope', '$route', 'someService', function ($scope, $route, someService) {
someService.getData.success(function(){});
}
And everything used to work fine... until yesterday when I realized that I needed to use resolve in my routes so that I can delay the rendering of my views until all data is returned from my datacontext service and all promised are resolved.
However, that means I have to change the syntax above to:
function someCtrl($scope, $route, someService) {
}
someCtrl.resolve = {
// get data from here
}
someCtrl.$inject = ['$scope', '$route', 'someService'];
So that in my route definition I can do:
controller: someCtrl,
resolve: someCtrl.resolve
I don't like the above syntax. I much preferred what I used to do (the minification-friendly syntax).
Now the problem is, using the new syntax, how do I assign someCtrl to the angular module 'myModule.controllers' that I had defined before ?
I know one way to handle pls see below code i have implemented in my project
Note:If you use module registered controller you have to use literal notation '' with controller name
-->route
$routeProvider.when('/Rally/:date/:id/:month', {
templateUrl: '/partials/RallyDetail.html', controller: 'rallydetailcontroller', resolve: {
rallydata: ['$http', '$route', function ($http, $route) {
return $http({
method: 'GET',
url: 'https://api.mongolab.com/api/1/databases/benisoftlabs/collections/RallyDetail?q={"Candidate":"' + $route.current.params.id + '","Month":"' + $route.current.params.month + '","Date":"' + $route.current.params.date + '"}&apiKey=50920bb9e4b010d72c561d8a'
});
}],
}
});
-->controller
App.controller('rallydetailcontroller',['$scope', 'rallydata', function ($scope, rallydata) {
$scope.rallyData = rallydata.data;
}]);

AngularJs ReferenceError: $http is not defined

I have the following Angular function:
$scope.updateStatus = function(user) {
$http({
url: user.update_path,
method: "POST",
data: {user_id: user.id, draft: true}
});
};
But whenever this function is called, I am getting ReferenceError: $http is not defined in my console. Can someone help me understanding what I am doing wrong here?
Probably you haven't injected $http service to your controller. There are several ways of doing that.
Please read this reference about DI. Then it gets very simple:
function MyController($scope, $http) {
// ... your code
}
I have gone through the same problem when I was using
myApp.controller('mainController', ['$scope', function($scope,) {
//$http was not working in this
}]);
I have changed the above code to given below. Remember to include $http(2 times) as given below.
myApp.controller('mainController', ['$scope','$http', function($scope,$http) {
//$http is working in this
}]);
and It has worked well.
Just to complete Amit Garg answer, there are several ways to inject dependencies in AngularJS.
You can also use $inject to add a dependency:
var MyController = function($scope, $http) {
// ...
}
MyController.$inject = ['$scope', '$http'];

Resources