Access AngularJS form in controller - angularjs

Is this the correct way of doing it? The main disadvantage is that I have to do this on each form and controller.
I have one form and want to access that form by storing a variable in a controller variable and then access it in my controller.
In my view im doing this:
<form name="formName">
<div ng-init="setForm(formName);" />
</form>
And in my controller i got
$scope.setForm = function (form) {
$scope.myForm = form;
}
Now after doing this I have a controller variable which is $scope.myForm.

The form will automatically be available via $scope, no need to explicitly save it.
If you however need to log it at controller initialization you need to wait for Angular to have processed it.
HTML:
<body ng-controller="MyController">
<form name="formName">
</form>
</body>
JS:
app.controller('MyController', function($scope, $timeout) {
$scope.$evalAsync(function() {
console.log($scope.formName);
});
});
Demo: http://plnkr.co/edit/wGPKKIGjlQ6Q4GT0aAC6?p=preview

Related

Not able to access ng-model variables when using ng-view

I have the following Form which I am including in the main app through ng-view
Form Snippet
<form action = "#" method="post" class="form-horizontal" id="commentForm" role="form">
<div class="form-group">
<div class="col-sm-10">
<textarea class="form-control" type="text" ng-model="userComment" placeholder="New Discussion Topic" rows="5"></textarea>
</div>
</div>
<div class="form-group" id="div_submitComment">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn" type="button" id="submitComment" ng-click="vm.addComment()">Submit comment</button>
</div>
</div>
</form>
Upon clicking the submit button, the controller function will be called. In the controller function, I am not able to access the variable $scope.userComment
Controller Snippet
(function () {
'use strict';
angular
.module('app')
.controller('DiscussionBoardController', DiscussionBoardController);
DiscussionBoardController.$inject = ['UserService', '$rootScope', '$scope', '$cookieStore', 'AuthenticationService'];
function DiscussionBoardController(UserService, $rootScope, $scope, $cookieStore, AuthenticationService) {
function addComment() {
$.getJSON(
"http://localhost/DBoardPage/server/discussion-board/postComment.php", // The server URL
{ userName: $scope.currentUser , userComment:$scope.userComment , commentID:0 }, // Data you want to pass to the server.
$scope.addCommentResponse // The function to call on completion.
);
};
/*End - Discussion Board related Functions*/
}
})();
Though I know that a child scope will be created when we use ng-include, ng-view and ng-repeat, I am not getting an example to explain the usage.
Please let me know how I can get around this preoblem
Are you sure it isn't $scope.currentUser that doesn't exist? You are using a variable that isn't declared.
Try adding:
$scope.currentUser = "";
$scope.userComment = "";
Since you are using AngularJS it might be a better idea creating your function the Angular way.
$scope.addComment = function(){....
If it still doesn't work show more of your setup.

window object not available on $scope in controller / link functions

I placed a kendo-window in my html.
according to the docs, the window object should be available on the scope.
now, I want to bind a listener to the window's activate event from within a controller that is declared inside the window. i.e.:
markup:
<body ng-app="app">
<div kendo-window='potatoWindow'>
<div ng-controller='PotatoController'>
here
</div>
</div>
js:
var app = angular.module("app", ["ngRoute", "kendo.directives"]);
app.controller("PotatoController", function($scope){
$scope.potatoWindow.bind("activate",
function () {
console.log("potato");
});
});
... but the window object (potatoWindow) is not found on the $scope during the controller.
Qs:
why is the window object not available? am i missing something?
if there is no way to access the window object - is there a way to get the same results by other means?
I think your kendo-window markup needs to be part of the controller markup.
Also, try using the k-on-activate binding and define your function in the controller like this:
MARKUP:
<div ng-controller='PotatoController'>
<div kendo-window='potatoWindow' k-on-activate='fry()'>
here
</div>
</div>
JS:
var app = angular.module("app", ["ngRoute", "kendo.directives"]);
app.controller("PotatoController", function($scope){
$scope.fry = function(e){
console.log('fried!');
};
});

difference between init function calling from controller initialization and from html page at rendering in angular js

what is the difference between init() method calling from controller initialization time and from html page at rendering in angular js ?
html partial:
<div ng-init="init()">
---
---
</div>
controller :
angular.module('masterJs')
.controller('SignupCtrl', function ($scope, $rootScope) {
$scope.init(){
//code here
}
});
here i am calling init() method from partial. what is the difference when we call init() from controller not from the html page like:
angular.module('masterJs')
.controller('SignupCtrl', function ($scope, $rootScope) {
$scope.init(){
//code here
}
$scope.init();
});
The difference is that when you have the ng-init in the HTML, the init() function will only be called during the actual render of the page. If for any reason that content needs to be re-rendered, the init() function will be called again.
When you call the init() function on the controller, it will only run one time (when the controller is created). According to angular's documentation, this is the best practice (avoid using ng-init).
Normally you use ng-init for intitializing a ng-repeat.
The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.
Example:
<script>
angular.module('initExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.list = [['a', 'b'], ['c', 'd']];
}]);
</script>
<div ng-controller="ExampleController">
<div ng-repeat="innerList in list" ng-init="outerIndex = $index">
<div ng-repeat="value in innerList" ng-init="innerIndex = $index">
<span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
</div>
</div>
</div>
The way you are using the init function, is inappropriate.

how to modularize angular code?

I have two DIVs, each one is a self-contained user control or partial view, if I want one team to work on dog div, the other team work on fox div. can each team have their own angular module, controller, view, etc ? If yes, can you show me a code snippet?
another question: if I want to these two DIVs loosely coupled, what is the best angular way to let them communicate ?
<body ng-app>
<div id="dog">
<input type="text" ng-model="name"/> {{name}}
</div>
<div id="fox">
</div>
</body>
Thank you!
For other new ng developer's reference, this is the final code, if you have better solution, please feel free to improve it.
<body ng-app="airborneApp">
<div id="dog" ng-controller="dogController">
<input type="text" ng-model="name" /> {{name}}
</div>
<div id="fox" ng-controller="foxController">
<input type="text" ng-model="name" /> {{name}}
</div>
<script>
angular.module('airborneApp', ["dogCompany", "foxCompany"]);
angular.module('dogCompany', []).
controller('dogController', ['$scope', function ($scope) {
$scope.name = 'hello dog';
}]);
angular.module('foxCompany', []).
controller('foxController', ['$scope', function ($scope) {
$scope.name = "hello fox";
}]);
</script>
</body>
You can make as many modules as you can, you just have to reference all of them as a dependency in you main App module definition (and load them in correct order)
app
angular.module('myApp', ['firstModule', 'secondModule'])
modules
angular.module('firstModule', []) // empty array as a second parameter creates new module instead of using existing one
.controller(...)
.directive(...)
angular.module('secondModule', [])
.controller(...)
.directive(...)
For communication between different modules, the simplest way is to inject $rootScope into all controllers.
But preferred way is to create a service in main app module, which will be injected into both modules
angular.module('myApp')
.factory('SharedData', function() {
var a = {},
b = {};
return {
a: a,
b: b
}
})
and then use it
angular.module('firstModule')
.controller('something', function($scope, SharedData) {
SharedData.a.data = 'new data';
})
angular.module('secondModule')
.controller('something else', function(SharedData) {
console.log(SharedData.a.data); //will output 'new data'
})
each div can have a separate controller using:
<div ng-controller="firstCtrl"></div>
<div ng-controller="secondCtrl"></div>
for the other part of your question see:
What's the correct way to communicate between controllers in AngularJS?

how to call parent method with dependencies in angularjs

I am trying to use div with ng-click for routing:
ng-click="go('/item/{{item.id}}').
I can call $parent.go or even go when using ParentCtrl. But ParentCtrl_2 does not work at all. I tried to look for some answers, but can't figure it out. What am I missing?
app.controller('ParentCtrl', function($scope) {
$scope.go = function(path) {
console.log(path);
}
}
);
app.controller('ParentCtrl_2', ['$scope', '$location',
function($scope, $location) {
$scope.go = function(path) {
$location.path(path);
}
}
]);
app.controller('ChildCtrl', ['$scope', '$routeParams',
function($scope, $routeParams) {
...
}
]);
There are number of unanswered questions here but, like what is the structure of your html ng-controller structure.
Also the call sytax in html is wrong for
ng-click="go('/item/{{item.id}}')
It should be
ng-click="go('/item/'+ item.id)"
Said that depending on where the ng-click is declared it would have access to parent methods. If you can access a method using $parent then you can access the method directly due to prototypal inheritance.
If structure is like
<div ng-controller='ParentCtrl'>
<div ng-controller='ParentCtrl_2'>
<div ng-controller='ChildCtrl'>
<!-- ng-click somewhere here -->
</div>
</div>
</div>
Then you access the ParentCtrl_2 method go whenever you call.
If it is
<div ng-controller='ParentCtrl'>
<div ng-controller='ParentCtrl_2'>
</div>
<div ng-controller='ChildCtrl'>
<!-- ng-click somewhere here -->
</div>
</div>
Then you have access to ParentCtrl method go method only.

Resources