AngularJS controller binding - angularjs

I'm new to AngularJs and I try to understand the basics of controller binding. lets say I have this in my html page:
<div ng-controller ="MainController">
<h2>{{message}}</h2>
</div>
Now, in my script file I have two options(as I saw in different tutorials):
1:
var myApp = angular.module('myApp',[]);
myApp.controller('MainController', ['$scope', function($scope) {
$scope.message = 'hello';
}]);
2:
var MainController = function($scope)
{
#scope.message = "Hello";
};
Offcourse I prefer the second approach however only the first option works for me. I'm working with AngularJS 1.4.4, could it be the second approach is now deprecated?
Thanks!

The second approach is just assigning the controller code to a variable, where in your first approach you pass it directly into the controller function. To make the second approach work, you'd have to pass that variable into the controller function as follows.
myApp.controller('MainController', MainController);
You're doing the same thing. I go with the second approach because I think it's cleaner. Check out John Papa's style guide for clean guidelines on how to write your Angular code.

Related

Confusion between $scope's in controller and its function?

I'm new to UI. I do have confusion between $scope's in AngularJS. Please refer below snippet.
var mainApp = angular.module("mainApp", []);
mainApp.controller(['$scope', function($scope) {
$scope.name = "John";
}]);
So, what's the difference between $scope and function($scope)? Also how can we relate both? Is it required to have $scope parameter? Please explain me with an example. I really appreciate that.
Thanks,
John
1.When you apply Minification of Following Angular JS code:
var mainApp = angular.module("mainApp", []);
mainApp.controller(['$scope','$log', function($scope,$log) {
$scope.name = "John";
$log.log("John");
}]);
Minified Version :
var mainApp=angular.module("mainApp",
[]);mainApp.controller(["$scope","$log",function(n,o)
{n.name="John",o.log("John")}]);
2.When you apply Minification of Following Angular JS code:
var mainApp = angular.module("mainApp", []);
mainApp.controller(function($scope,$log) {
$scope.name = "John";
$log.log("John");
});
Minified Version :
var mainApp=angular.module("mainApp",[]);mainApp.controller(function(n,a)
{n.name="John",a.log("John")});
3.When you apply Minification of Following Angular JS code:
var mainApp = angular.module("mainApp", []);
mainApp.controller(function($log,$scope) {
$scope.name = "John";
$log.log("John");
});
Minified Version :
var mainApp=angular.module("mainApp",[]);mainApp.controller(function(n,a)
{n.name="John",a.log("John")});
You will Notice in Ex-2 and Ex-3 that you have interchanged the Dependency place of $scope and $log then also your minified version is the same ,this will give you dependency Injection error ,so we place a String value as String Value can't be minified as you can see in Ex-1.
It is not required to have $scope each time you define your controller but $scope provides important functionality like binding the HTML (view) and the JavaScript (controller). .
https://docs.angularjs.org/guide/scope
what's the difference between $scope and function($scope)?
When you do
mainApp
.controller(
['$scope', //line 1
function($scope) //line 2
{
}
]);
In line 1 it refers to $scope, which is an object that refers to the application model
In line 2 it is the variable (conveniently called $scope too) in which the (mentioned above) $scope object is injected. This variable can have any other name, $scope is used as a way to keep a suggestive reference through the whole code.
For instance, your example would work too if I change its name to myFunnyScope like this:
var mainApp = angular.module("mainApp", []);
mainApp.controller(['$scope', function(myFunnyScope) {
myFunnyScope.name = "John";
}]);
Also how can we relate both?
Taking as reference my previously posted snippet, you can tell the $scope object is being injected in the myFunnyScope variable, it means you use myFunnyScope as if it were $scope itself.
Is it required to have $scope parameter?
As long as you need to get access to all benefits provided by the mentioned $scope object, when you do minification it is required to inject the object ([$scope, ...) into the holder (function($scope) { ...) in order to not get the AngularJS application broken. Otherwise, no, you don't need to inject the object, but then you have to explicitly call it $scope in the function parameter so AngularJS knows it has to inject the $scope object inside it. This rule applies not only to $scope, but to all other AngularJS related services, factories, etc such as $timeout, $window$, $location, etc.
You might want to read about the AngularJS injection mechanism and consider using the controller as syntax for reasons explained here if you do not want to use $scope directly.

Can't change 1 arg in controller in angularjs?

This is my angular code.
angular.module("app", []).controller("ctrl", function($scope){
$scope.name = "Name";
});
but, when I chaged the paramerter thats not working.
angular.module("app", []).controller("ctrl", function($para){
$para.name = "Name";
});
How to make it work and can't we use this in our other function?
Angular uses dependency injection based on the given parameter name. It doesn't know $para, so it won't get injected. You can however use the array notation where you explicitly say the name of the service to inject. The array notation is also necessary if you minimize your javascript code, so that angular still knows what to inject when your variables get renamed to a, b etc:
angular.module("app", []).controller("ctrl", ["$scope", function($para){
// $para is the $scope object
$para.name = "Name";
}]);
If your $para is a service, you have to register it so that angular knows what to inject:
angular.module("app", [])
.service("$para", function() {
//
})
.controller("ctrl", function($para){
$para.name = "Name";
});
The scope is the binding part between the HTML (view) and the JavaScript (controller). It is a special in angular.
Please read this https://www.w3schools.com/angular/angular_scopes.asp
'$scope' is a special service in AngularJS.
You can, however, create your own service '$para' and inject it if you want.
Check this.
Also, if you don't want to use '$scope', you can use the alternative 'controller as' syntax.
Read about it here.

Best way of defining controller in angularJs

I am new to angularJs. I am confused which one is best way to create a controller for ng-app="mainApp". In programming other programming languages that I had worked on suggest to keep relative data together. But in angularJs it's considered best practice to have new module for controllers when we can define controller over main app module. If we create controller on mainApp it will keep controller and bind which is what we want in other languages.
var myapp = angular.module("mainApp", []);
myapp.controller("testController", function($scope)
{
$scope.value = "test";
})
//OR
angular.module("mainApp", ["moduleController"]);
angular.module("moduleController", []).controller("testController", function($scope){
$scope.value = "test";
})
For production environment which one should be used.??
Option 1:
var myapp = angular.module("mainApp",[]);
myapp.controller("testController",function($scope)
{
$scope.value="test";
})
Option 2:
angular.module("mainApp", ["moduleController"]);
angular.module("moduleController",[]).controller("testController",function($scope){
$scope.value="test";
})
Option 2 is better because this will allow you to write your controllers in separate files. As a result your code will be more readable. It'll also help you if you want to reuse your controllers in other AngularJS projects.
For example, you can write the following code in one file e.g app.js:
angular.module('mainApp',['ngRoute', 'appController']);
And you can write the controller in another file e.g controllers.js:
var appController= angular.module('appController', []);
appController.controller('testController', ['$scope',
function($scope) {
$scope.value="test";
}
]);
Now, you can reuse the controllers in another project by just adding the controllers.js file in the project and adding dependency to appController in the app.js file.
Neither, none of them will run in production environment where all script will be minified. Angular's injector subsystem is able to find and resolve $scope, $location, $etc and provide them to the component as requested.
myapp.controller("testController",function($scope)
{
$scope.value="test";
})
However, upon minification, the code above will end up looking something like:
a.controller("testController",function(b)
{
b.value="test";
})
which would cause the dependency injection to fail and result in a runtime error.
You will have to use it as below:
var myapp=angular.module("mainApp",[]);
myapp.controller("testController", ['$scope',function($scope)
{
$scope.value="test";
}]);
In this case, the controller function is initialized inside of an array after a list of each dependency as string literals. This ensure dependency injection is properly maintained, even through minification or uglification.

How do I get this AngularJS service working in my code?

Here is the code for my service. It is taken almost exactly from the first answer here.
var myApp = angular.module('myApp', ['ngRoute']);
myApp.service('sharedProperties',function(){
var property = "First";
return{
getProperty:function(){
return property;
},
setProperty:function(value){
property = value;
}
};
});
Here is the JSFiddle that shows my code in full and it not working.
The error I get is:
"Error: sharedProperties is not defined
For the line that the alert is on. I am just using an alert as a mere example of showing that the service is working before I extend the code further.
Anyone know why this simple example of a service is not working? I've thoroughly went over the code to make sure there are no typos or anything silly like that.
The answer that I linked has a JSFIDDLE that uses an older version of AngularJS. I was able to replace it with the version Angular being used in my JSFIDDLE and it still worked fine so it doesn't seem to be a version issue.
You need to inject the service to your controller:
myApp.controller('mainController', function($scope, sharedProperties) {
(Minification safe syntax)
myApp.controller('mainController', ["$scope", "sharedProperties", function($scope, sharedProperties) {
Working fiddle: http://jsfiddle.net/b2fCE/733/
You need to inject the service in your controller.
Here is the fiddle https://jsfiddle.net/b2fCE/732/
myApp.controller('mainController', function($scope, sharedProperties) {
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
alert(sharedProperties.getProperty());
});

Angular JS controller

I am a little confused in the syntax for the controller in angular js:
Both the following controller work when I use {{ and }}.
Could someone tell me what is use of the parameters $scope and $filter before the function($scope..), the one in bold. Also when I remove one of these, I dont get the output.
'MyController1', ['$scope', '$filter',function($scope
app.controller('MyController1', ['$scope', '$filter',function($scope, $filter) {
$scope.an = $filter('uppercase') ("ankurbhatia");
}]);
Here I have removed the $scope and $filter before the function but it still works.
app.controller('DemoController',
function($scope, $filter) {
$scope.an= $filter('uppercase')('Ari');
});
It is usefull if you minify your JavaScript. If you state the "stringified" variable before, the minified JS will still find what the minifed variable should be.
Your JavaScript minifed will be
app.controller("MyController1",["$scope","$filter",function(r,a){r.an=a("uppercase")("ankurbhatia")}]);
If you dont specify the string before, it will look like this:
app.controller("MyController1",function(o,r){o.an=r("uppercase")("ankurbhatia")});
Se the section "A Note on Minification"
at https://docs.angularjs.org/tutorial/step_05

Resources