How to initialise value in controller with Angular js ? - angularjs

How to initialise value inside controller function with AngularJS tried multiple time but not getting proper answer??

You can inject $scope in your controller function. Then you can define any variable inside $scope.
Example
.controller('TestController', ['$scope', function($scope) {
$scope.message = 'Hello';
}])
As you can see in the above example I have injected $scope to TestController and defined message variable inside it.
Note that all the variables defined in a controller scope are accessable by the view belonging to that controller. So you can access the value of $scope.message in your DOM as
<div ng-controller="TestController">
{{message}}
</div>
On the screen you will see the text Hello

Related

angularjs components getting a form inside template

so I have a component with a template containing a form.
mycomponent.html:
<div>
<form name="myForm">
<!-- more html code -->
</form>
</div>
How can I access myForm inside the component controller?
Currently I'm injecting $scope to get it from that.
Or is that the only way to get the form?
Edit: Added some code to better illustrate in javascript
angular.module('example')
.component('myComponent', {
templateUrl: 'mycomponent.html',
controller: function($scope) {
$scope.myForm // This works
this.myForm // undefined, can I access it through the component scope instead of $scope somehow?
}
});
The name attribute of a form is what angular uses to decide what to bind to. So, if you're using the controllerAs syntax, you have to use that in the form name:
<body ng-controller="MainCtrl as vm">
<form name='vm.myForm'>
</form>
</body>
This will allow you to refer to it in your controller without using $scope, but only after the controller has been successfully created:
app.controller('MainCtrl', function($scope, $timeout) {
var vm = this;
console.log(vm.myForm); // undefined
$timeout(function() {
console.log(vm.myForm); // FormController object
}, 100);
});
Here is a working plunk.
Use the name syntax but also a components postLink lifecycle hook, that function is called once a template and controller have been connected see https://docs.angularjs.org/guide/component

Can't access $parent from ng-included controller

I'm pretty new to Angular and I'm trying to build an app.
I use ng-include to insert my view, depending on the currentURL variable of my main controller.
When I try to access the main controller via $parent from the ng-included file, all I get is undefined.
My goal is to change the currentURL variable to update the view.
Here is my code:
index.html
<body ng-controller="mainCtrl as main">
currentURL : {{main.currentURL}}
<div ng-include="main.currentURL"></div>
<script src="/vendors/angular.min.js"></script>
<script src="/modules/login.js"></script>
<script src="app.js"></script>
</body>
app.js
angular
.module('mcaApp', ['login'])
.controller('mainCtrl', mainCtrl);
function mainCtrl() {
var vm = this,
baseURL = 'views/';
vm.currentURL = baseURL + 'login.html';
}
views/login.html
<div ng-controller="loginCtrl as login">
<h1>LOGIN</h1>
</div>
modules/login.js
angular
.module('login', [])
.controller('loginCtrl', loginCtrl);
function loginCtrl() {
var vm = this;
console.log(vm.$parent); // undefined
}
As you want to access mainCtrl which was inside loginCtrl controller then you need use $parent to access parent controller scope.
But the thing is you are loading loginCtrl controller view using ng-include so your controller is loaded in the child scope of the mainCtrl, because ng-include create a child scope from current scope.
For that reason you need use $parent.$parent to access mainCtrl scope from loginCtrl
Code
function loginCtrl($scope) {
var vm = this;
console.log($scope.$parent.$parent); // this would contain mainCtrl
}
Better approach would be to use controllerAs syntax or follow dot rule while defining objects so that prototypal inheritance gets followed.

Angularjs $scope value updated in second controller not visible in view

I have one html file and a controller assigned via $routeProvider
.when('/page/:pageId', {
templateUrl: 'xxxx.html',
controller: 'PageCtrl'
})
and in the controller.js file i am accessing the value of pageId using $routeParams in 'PageCtrl' function.
pageId = $routeParams.pageId;
and in view the html is
<div ng-controller="headerController">
{{page.pageId}}
</div>
so in html i want to display the pageId, if pageId is passed in the url.
so here my question is once the pageId is passed its going correctly to the pageCtrl in Js and pageId scope value assigned, and am also able to assign the same scope value to the second controller 'headerController' by $controller('headerController', {$scope: $scope});
able to see that scope value is getting updated from one controller to another controller but my problem is that scope value which is updated, unable to view in html ({{page.pageId}})
The problem is that your controller is getting instantiated twice: once from your $controller call and another time from the ng-controller directive in your view, each time with a difference scope, where the latter "wins" as far as what shows up in your view goes.
Consider this small demo:
JS
.controller('FirstController', function($scope, $controller){
console.log('FirstController', $scope.$id); // logs 003
$scope.pageId = '12345';
$controller('SecondController', {$scope: $scope});
})
.controller('SecondController', function($scope){
console.log('SecondController', $scope.$id); // logs 003 & 004
$scope.scopeId = $scope.$id; // second scope "wins", appears in view
});
HTML
<div ng-controller="FirstController"></div>
<!-- {{scopeId}} outputs a value while {{pageId}} does not -->
<div ng-controller="SecondController">Scope: {{scopeId}} Page: {{pageId}}</div>
A better solution is to use a service to share data between controllers.

Passing javascript variables from controller to partial file in AngularJs

I am new to AngularJs. I have put a url value in the scope variable inside a controller. This value should be used in the partial file corresponding to the controller inside a javascript function. How can I achieve this in AngularJs.
Code snippet is given below for reference:
Config code:
myApp.config(function ($routeProvider){
$routeProvider.
when('/state-details/:id',
{
controller:'controllers.StateDetailsCtrl',
templateUrl:'/partials/state-details.html'
})
.... More routes defined below...
Inside the controller:
controllers.StateDetailsCtrl= function($scope, $routeParams, $http){
$scope.testURL='http://www.google.com'
.... More values set in the scope..
Inside the state-details partial file:
<script>
// how to get the value of the testURL defined in the scope?
</script>
Please let me know how to get this working?
If you need to add additional javascript into a partial html file, then it just like screams to use a directive.
There you can inherit the whole ctrl scope or create a isolated scope.
https://docs.angularjs.org/guide/directive

$routeParams is empty in main controller

I have this piece of layout html:
<body ng-controller="MainController">
<div id="terminal"></div>
<div ng-view></div>
<!-- including scripts -->
</body>
Now apparently, when I try to use $routeParams in MainController, it's always empty. It's important to note that MainController is supposed to be in effect in every possible route; therefore I'm not defining it in my app.js. I mean, I'm not defining it here:
$routeProvider.when("/view1", {
templateUrl: "partials/partial1.html"
controller: "MyCtrl1"
})
$routeProvider.when("/view2", {
templateUrl: "partials/partial2.html"
controller: "MyCtrl2"
})
// I'm not defining MainController here!!
In fact, I think my problem is perfectly the same as this one: https://groups.google.com/forum/#!topic/angular/ib2wHQozeNE
However, I still don't get how to get route parameters in my main controller...
EDIT:
What I meant was that I'm not associating my MainController with any specific route. It's defined; and it's the parent controller of all other controllers. What I'm trying to know is that when you go to a URL like /whatever, which is matched by a route like /:whatever, why is it that only the sub-controller is able to access the route parameter, whereas the main controller is not? How do I get the :whatever route parameter in my main controller?
The $routeParams service is populated asynchronously. This means it will typically appear empty when first used in a controller.
To be notified when $routeParams has been populated, subscribe to the $routeChangeSuccess event on the $scope. (If you're in a component that doesn't have access to a child $scope, e.g., a service or a factory, you can inject and use $rootScope instead.)
module.controller('FooCtrl', function($scope, $routeParams) {
$scope.$on('$routeChangeSuccess', function() {
// $routeParams should be populated here
});
);
Controllers used by a route, or within a template included by a route, will have immediate access to the fully-populated $routeParams because ng-view waits for the $routeChangeSuccess event before continuing. (It has to wait, since it needs the route information in order to decide which template/controller to even load.)
If you know your controller will be used inside of ng-view, you won't need to wait for the routing event. If you know your controller will not, you will. If you're not sure, you'll have to explicitly allow for both possibilities. Subscribing to $routeChangeSuccess will not be enough; you will only see the event if $routeParams wasn't already populated:
module.controller('FooCtrl', function($scope, $routeParams) {
// $routeParams will already be populated
// here if this controller is used within ng-view
$scope.$on('$routeChangeSuccess', function() {
// $routeParams will be populated here if
// this controller is used outside ng-view
});
);
As an alternate to the $timeout that plong0 mentioned...
You can also inject the $route service which will show your params immediately.
angular.module('MyModule')
.controller('MainCtrl', function ($scope, $route) {
console.log('routeParams:'+JSON.stringify($route.current.params));
});
I have the same problem.
What I discovered is that, $routeParams take some time to load in the Main Controller, it probably initiate the Main Controller first and then set $routeParams at the Child Controller. I did a workaround for it creating a method in the Main Controller $scope and pass $routeParams through it in the Child Controllers:
angular.module('MyModule')
.controller('MainController', ["$scope", function ($scope) {
$scope.parentMethod = function($routeParams) {
//do stuff
}
}]);
angular.module('MyModule')
.controller('MyCtrl1', ["$scope", function ($scope) {
$scope.parentMethod($routeParams);
}]);
angular.module('MyModule')
.controller('MyCtrl2', ["$scope", function ($scope) {
$scope.parentMethod($routeParams);
}]);
had the same problem, and building off what Andre mentioned in his answer about $routeParams taking a moment to load in the main controller, I just put it in a timeout inside my MainCtrl.
angular.module('MyModule')
.controller('MainCtrl', function ($scope, $routeParams, $timeout) {
$timeout(function(){
// do stuff with $routeParams
console.log('routeParams:'+JSON.stringify($routeParams));
}, 20);
});
20ms delay to use $routeParams is not even noticeable, and less than that seems to have inconsistent results.
More specifically about my problem, I was confused because I had the exact same setup working with a different project structure (yo cg-angular) and when I rebuilt my project (yo angular-fullstack) I started experiencing the problem.
You have at least two problems here:
with $routeParams you get the route parameters, which you didn't define
the file where you define a main controller doesn't really matter. the important thing is in which module/function
The parameters have to be defined with the $routeProvider with the syntax :paramName:
$routeProvider.when("/view2/name1/:a/name2/:b"
and then you can retrieve them with $routeParams.paramName.
You can also use the query parameters, like index.html?k1=v1&k2=v2.
app.js is the file where you'd normally define dependencies and configuration (that's why you'd have there the app module .config block) and it contains the application module:
var myapp = angular.module(...);
This module can have other modules as dependencies, like directives or services, or a module per feature.
A simple approach is to have a module to encapsulate controllers. An approach closer to your original code is putting at least one controller in the main module:
myapp.controller('MainCtrl', function ($scope) {...}
Maybe you defined the controller as a global function? function MainCtrl() {...}? This pollutes the global namespace. avoid it.
Defining your controller in the main module will not make it "to take effect in all routes". This has to be defined with $routeProvider or make the controller of each route "inherit" from the main controller. This way, the controller of each route is instantiated after the route has changed, whereas the main controller is instantiated only once, when the line ng-controller="MainCtrl" is reached (which happens only once, during application startup)
You can simply pass values of $routeParams defined into your controller into the $rootScope
.controller('MainCtrl', function ($scope, $routeParams, MainFactory, $rootScope) {
$scope.contents = MainFactory.getThing($routeParams.id);
$rootScope.total = MainFactory.getMax(); // Send total to the rootScope
}
and inject $rootScope in your IndexCtrl (related to the index.html)
.controller('IndexCtrl', function($scope, $rootScope){
// Some code
});

Resources