controller use $scope? custom service use this? - angularjs

I found in Controller, we use $scope, here is the link (http://www.w3schools.com/angular/tryit.asp?filename=try_ng_controller).
I change $scope to this, it cannot work.
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
However, I found in Service, we use this, here is the link (http://www.w3schools.com/angular/tryit.asp?filename=try_ng_services_custom).
In hexafy service, I change this to $scope, it cannot work.
<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.controller('myCtrl', function($scope, hexafy) {
$scope.hex = hexafy.myFunc(255);
});
</script>
Does my above summary correct? If not, what should be correct summary considering all kinds of possible.

You can use this instead of $scope in controller as well. They have brought in controller as syntax(from Angular 1.2). You can attach data to this(Here controller holds the data). But internally it will be attached to $scope only, but you don't have to attach it manually. It has to be declared in html like this , controller is declared as main , so we have to refer to data in html using main.
<div ng-controller="MainCtrl as main">
{{ main.title }}
</div>
app.controller('MainCtrl', function ($scope) {
this.title = 'Some title';
console.log("Title" + $scope.main.title); // It will print some title in the console.
});

Related

How can i get a variable from one controller and then pass the same variable to view

I have two controllers ParentController and ChildController I have a variable in ParentController and i need to get that variable to ChildController and then i need to pass it to the view and one more thing is i should not use the $scope in child controller and parentController. Is it possible ?if not is there any way to use it with out $scope.
app.controller('ParentController', function($scope) {
$scope.exampleVariable = "test";
});
app.controller('ChildController', function($scope, $controller) {
var someScopeVariable = this;
$controller('ParentController', {$scope: someScopeVariable });
console.log(someScopeVariable.exampleVariable)
someScopeVariable.exampleVariable = "Updatetest";
});
Now in my html view i need to use exampleVariable
like this
<div ng-controller="ChildController as child">
<h1>{{child.exampleVariable}}</h1>
</div>
How can i get the value from parentcontroller to html view.
You can always use a service to share data between controllers.
create a service
app.service('myservice', function() {
var myVar;
this.setMyVar = function(value){
this.myVar = value
}
this.getMyVar = function(){
return this.myVar;
}
});
pass it as a dependency and you can have the value shared.
app.controller('ParentController',['$scope', 'myservice', function($scope, myservice) {
$scope.exampleVariable = "test";
myservice.setMyVar("test");
}]);
you can pass it to other controller as a dependency too and you can do a getMyVar there!!
You can use Broadcast and On in the Controller-
app.controller('ParentController', function($scope) {
var self = this;
$scope.$broadcast('exampleVariable', 'test');
});
and in child controller -
app.controller('ChildController', function($scope, $controller) {
var someScopeVariable = this;
$controller('ParentController', {$scope: someScopeVariable });
console.log(someScopeVariable.exampleVariable)
$scope.$on('exampleVariable', function(event, data) {
someScopeVariable.exampleVariable = data;
});
});
There are some ways you can achieve this.
1. Through $rootScope.
2. By Creating Service.
3. Inheriting parent controller to children controller.
2 & 3 are already provided in other answers. Follow this if you want to achieve it using $rootScope.
JS :
var app = angular.module('myApp', []);
app.controller('ParentController', function($scope, $rootScope) {
$rootScope.exampleVariable = "test";
});
app.controller('ChildController', function($scope) {
});
HTML :
<div ng-controller="ParentController">
Parent Controller : {{exampleVariable}}
<hr/>
</div>
<div ng-controller="ChildController">
Children Controller : {{exampleVariable}}
</div>
DEMO LINK.
Note : You can also override the scope variable in children controller by adding the below code in ChildController :
$scope.exampleVariable = "overriding...";

Angularjs: Injecting one controller in another failed

I have this controller A which I'm trying to inject in every other controller.
What controller A does is, it communicates with a factory (which does some authentication services, communicates with database)
My factory looks like this and I named it myFactoryServices.js and included the link to it in my index page.
(function() {
angular
.module('myApp.myFactoryServices', [])
.factory('FactoryService', ["$http", "$location", function($http, $location){
var my = this;
my.someFunction = function()
{
//communiate with backend and return data
}
return my;
}]);
})();
and my Controller A looks like this:
(function() {
angular
.module('myApp.ControlA', [])
.controller('ControllerA', function($scope,$routeParams, FactoryService) {
var my = this;
FactoryService.someFunction();
});
})();
And I am trying to inject this controller in every other controller, but it does not work. I am pretty new to this kind of programming, can anyone tell me where I made mistake?
This is how I tried injecting a controller into another.
(function() {
angular
.module('myApp.ControlB', [])
.factory('ControllerBService', function($http) {
var baseUrl = 'backendurl/';
return {
getInfo: function() {
return $http.get(baseUrl+ 'getInfo');
}
};
})
.controller('ControllerB', function($scope,$routeParams, ControllerBService,ControllerA) {
var my = this;
});
})();
No error is coming, and the controller is not getting injected as I am not able to use those factory services. is this the correct method?
First of all you cannot inject controller to another controller, and One simple solution would be, instead of having each angular modules for each components, declare a module and add the factory service to controllers as dependency.
Code:
var app = angular.module('myApp', []);
app.factory('FactoryService', ["$http", "$location", function($http, $location){
var my = this;
my.someFunction = function()
{
//communiate with backend and return data
}
return my;
}]);
app.controller('ControllerA', function($scope,$routeParams, FactoryService)
{
var my = this;
FactoryService.someFunction();
});
app.controller('ControllerB', function($scope,$routeParams, FactoryService)
{
var my = this;
FactoryService.someFunction();
});
Controllers are not injectable, because controller is not singleton. Controllers are constructor functions used to create instances of controllers. For example you can have multiple instances of one controller in your app:
angular.module('app', []);
angular
.module('app')
.controller('Example', function () {
this.x = Math.random();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
<div ng-app="app">
First instance: <br>
<div ng-controller="Example as Ex1">
{{Ex1.x}}
</div>
Second instance: <br>
<div ng-controller="Example as Ex2">
{{Ex2.x}}
</div>
</div>
So if you want to share some behavior between controller you should use factory instead.
To inject a controller into another controller, use the $controller service.
app.controller('ControllerB', function($scope,$routeParams, $controller) {
var my = this;
$scope.ctrlA = $controller("ControllerA", {$scope: $scope});
});
The above example creates an instance of ControllerA as ctrlA with its $scope injected with the scope of the parent controller.
For more information, see AngularJS $controller Service API Reference.

Do I always need to inject $location to use it in AngularJS?

I'm using angular declarations without using or injecting $scope var, but with this. declarations
var app = angular.module('myApp', []);
app.controller('myCtrl', myCtrlFunction);
function myCtrlFunction() {
this.myUrl = "This is myUrl content";
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl as vm">
<p>Here I put my var myUrl:</p>
<h3>{{vm.myUrl}}</h3>
</div>
It works ok but I can't figure out how to access '$location' so this works after minification
var app = angular.module('myApp', []);
app.controller('myCtrl', myCtrlFunction);
function myCtrlFunction() {
this.myUrl = $location.absUrl();
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl as vm">
<p>Here I put my var myUrl:</p>
<h3>{{vm.myUrl}}</h3>
</div>
Do I need to change the way I declare the contents of myCtrlFunction() ?
Yes, because it has dependency injection. In your current setup, your controller requires $location to be a global variable. Also, you need to supply a an array with string values for the parameter names, so angular still knows what to inject after the parameters are changed by minification algorithms.
So, use either one of those setups:
var app = angular.module('myApp', []);
app.controller('myCtrl', ['$location', myCtrlFunction]);
function myCtrlFunction($location) {
this.myUrl = "This is myUrl content";
}
or:
var app = angular.module('myApp', []);
app.controller('myCtrl', myCtrlFunction);
function myCtrlFunction($location) {
this.myUrl = "This is myUrl content";
}
// tell angular what parameters are expected
myCtrlFunction.$inject = ['$location'];
More about dependency injection in Angular.
You need to inject $location.
var app = angular.module('myApp', []);
app.controller('myCtrl', myCtrlFunction);
function myCtrlFunction(**$location**) {
this.myUrl = $location.absUrl();
}
You got away with the previous version because you weren't actually using the $scope keyword. But with $location you are specifically using it, so you need to inject it.

angular js alert by click donot work

i am new to AngularJS so please forgive me this dump question.
i have error
Cannot set property 'test' of undefined
angularjs
var App = angular.module('StartModule', []);
App.controller('ModalDemoCtrl', [
function($scope) {
$scope.test = function() {
alert("12312");
}
}
]);
html
<body ng-app="StartModule">
<div ng-controller="ModalDemoCtrl">
<div ng-click="test()">11111</div>
</div>
<body>
You just miss $scope to controller's second argument:
var App = angular.module('StartModule', []);
App.controller('ModalDemoCtrl', [ $scope, function($scope) {
$scope.test = function() {
alert("12312");
}
}]);
You're missing the $scope dependency, you need to inject it in your controller :
App.controller('ModalDemoCtrl', ['$scope'
function($scope) {
That's why the $scope variable is undefined, you're not actually injecting any dependency in it.
This uses the Inline Array Annotation: https://docs.angularjs.org/guide/di

Angularjs - Calling only one of many subcontrollers/ multiple controllers

I have an index page wherein I define two controllers. I want to call one main controller always (should be rendered always) and the other is called only for specific sub URL calls. Should I make one nested within another, or I can keep them independent of each other? I don't have access to change routes or anything, only the controller.
Right now when I use the template (HTML) mentioned, it calls/renders both controllers, even though url is say /index
Only for /index/subPage, I want both controllers to be rendering.
/index
/index/subPage
HTML:
<div ng-controller="MainCtl" ng-init=initMain()>
<p> Within ctller2 {{results}} </p>
</div>
<div ng-controller="Ctller2"> <!-- should not be displayed unless /subPage/mainUrl is rendering -->
<p> Within ctller2 {{results}} </p>
</div>
JS:
app.controller('MainCtl', ['$scope', '$http', '$location', function ($scope, $http, $location) {
$http.get('xx/mainUrl').then(function(data) {
$scope.results = someDataJSON;
console.log(someDataJSON);
});
$scope.initMain = function() {
$scope.initMethods();
}
}]);
app.controller('Ctller2', ['$scope', '$http', '$location', function ($scope, $http, $location) {
// This controller gets initialized/rendered/called even when xx/mainUrl is called, and when xx/subPage/mainUrl is called too..
$http.get('xx/subPage/mainUrl').then(function(data) {
$scope.results = someDataJSON;
console.log(someDataJSON);
})
$http.get('xx/subPage').then(function(data) {
$scope.results = data.data;
console.log(data);
})
angular.element(document).ready(function () {
alert('Hello from SubCtl, moving over from main controller to here');
});
}]);
What am I doing wrong? I'm new to Angular.js
You can conditionally initiate a controller using ng-if. So you could try something like this:
<body ng-controller="MainCtrl">
<div ng-controller="ctrl1">{{hello}}</div>
<div ng-controller="ctrl2" ng-if="showCtrl2">{{hello}}</div>
</body>
and then set the value of the variable in a parent controller by checking the current url using $location.path()
var app = angular.module('plunker', []);
app.config(function($locationProvider){
$locationProvider.html5Mode(true);
});
app.controller('MainCtrl', function($scope, $location) {
$scope.showCtrl2 = ($location.path() === 'my path');
});
app.controller('ctrl1', function($scope){
$scope.hello = 'ctrl1 says hello';
});
app.controller('ctrl2', function($scope){
$scope.hello = 'ctrl2 says hello';
});
But it's a bit hacky and for a larger project a more robust solution would require using something like ui.router.

Resources