var loginModule = angular.module("loginModule", ['ngRoute']);
loginModule.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/LoginCredential', {
templateUrl: 'login_credential.html',
controller: ''
}).
when('/SecurityQuestionPage', {
templateUrl: 'security_question.html',
controller: ''
}).
otherwise({
redirectTo: '/LoginCredential'
});
}]);
var loginCredController = loginModule.controller('loginCredController', ['$scope', '$http', function ($scope, $http) {
debugger;
$scope.loginData = {};
$scope.submit = function (LoginForm, loginData)
{
debugger;
var uname = loginData.username;
var pwd = loginData.password;
var lData = 'username='+uname+'&'+'password='+pwd
var request = $http({
method: "post",
url: "http://localhost:53738/Login?response_type=code&client_id=peopleworks&redirect_uri=google.com",
data: lData
});
request.success(
function (response) {
debugger;
}
);
}
}]);
this is login.js file. these are my views login.html and login_credential.html
login.html
<!DOCTYPE html>
<html>
<head>
<script src="Peopleworks/Scripts/angular.min.js"></script>
<script src="Peopleworks/Scripts/angular-route.min.js"></script>
<script src="Peopleworks/Lib/peopleworksLogin.js"></script>
</head>
<body>
<div data-ng-app="loginModule">
<div ng-view=""></div>
</div>
</body>
</html>
and
login_credential.html
<div data-ng-controller ="loginCredController">
<table>
<form method="post" name="LoginForm" ng-submit="submit(LoginForm, loginData)" novalidate>
<tr><td>Username</td><td><input id="username" name="username" ng-model="loginData.username" type="text" /></td>
<tr><td>Password</td><td><input id="password" name="password" ng-model="loginData.password" type="password" /></td>
<tr><td><button type="submit">Login</button>
</form>
</table>
</div>
problem is when I click submit the method in controller is not working... can anyone help me?
You have html markup wrong. Try closing tr and td tags properly and move form tag out of table tag in such a way that table reside inside form not the other way.
No need of "var loginCredController="
Simple use :-
loginModule.controller('loginCredController', ['$scope', '$http', function ($scope, $http){
...
...
}
From angularjs docs form
You can use one of the following two ways to specify what JavaScript method should be called when a form is submitted:
ngSubmit directive on the form element
ngClick directive on the first button or input field of type submit (input[type=submit])
To prevent double execution of the handler, use only one of the ngSubmit or ngClick directives.
This is because of the following form submission rules in the HTML specification:
If a form has only one input field then hitting enter in this field triggers form submit (ngSubmit)
if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter doesn't trigger submit
if a form has one or more input fields and one or more buttons or input[type=submit] then hitting enter in any of the input fields will trigger the click handler on the first button or input[type=submit] (ngClick) and a submit handler on the enclosing form (ngSubmit)
Note that ngClick events will occur before the model is updated. Use ngSubmit to have access to the updated model.
Use either ng-submit or input[type=submit].
Related
I have the following code structure
index.html
<body ng-app="jobPortalApp" ng-controller="mainController">
<div ui-view></div>
</body>
then following is my homepage.html template
<div id=header>
</div>
<div ui-view>
<input type="text" ng-model="test">Test</input>
<input type="submit" ng-click="signup()">
</div>
<footer>
</footer>
my angular module file is as follows
var jobPortalApp = angular.module('jobPortalApp',['ui.router']);
jobPortalApp.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider
.otherwise('/');
$stateProvider
.state('home',
{
url:'/',
templateUrl: './templates/homepage.html',
controller: 'controllerHome'
})
}).controller('mainController', function(){});
following is my home controller
jobPortalApp.controller('controllerHome',function($scope, $http) {
$scope.test="";
$scope.signup = function() {
console.log($scope.test);
}
});
Required:
I want the changed value of test in my controllerHome after the user clicks on signup
Problem:
console.log outputs blank and if I remove $scope.test="";then outputs undefined. I want the changed value of test in my controller.
You usually shouldn't bind directly to $scope due to issues with prototypal inheritance. When trying to read a value from a child scope, if the value doesn't exist you end up reading from the parent scope. But as soon as you write, you write to the child scope. Does it work if you bind to an object instead?
$scope.data = {
test: ""
};
<input type="text" ng-model="data.test">Test</input>
As an alternative, you may also want to look at the controllerAs option for your route:
controllerAs: "ctrl"
Then in your controller:
this.test = "";
And in your template:
<input type="text" ng-model="ctrl.test">Test</input>
I have a simple 1-page app design with two inputs in a static sidebar and an ng-view in which I load JSON data via a $http request in the controller. I'm using ngRoute to load different templates into the view.
This is sample code for my controller:
someModule.controller('JobPostingsCtrl', function($scope, $http) {
$scope.cityFilter = function() {
$http.get("dir/"+$scope.locationFilter+".json")
.then(function(res){
$scope.jobs = res.data;
});
};
$scope.searchFilter = function (jobposting) {
var keyword = new RegExp($scope.keyword, 'i');
return !$scope.keyword || keyword.test(jobposting.title);
};
$scope.locationFilter = $scope.locationFilter || 'all';
$http.get("dir/"+$scope.locationFilter+".json")
.then(function(res){
$scope.jobs = res.data;
});
});
In my index.html I mark up the sidebar with the input fields that are models for locationFilter and keyword:
<input type="search" name="search" id="search" ng-model="keyword">
<input type="search" name="location" id="location" ng-model="locationFilter">
<button id="go" ng-click="cityFilter();">Click</button>
On load, the view displays the 'all' data normally and the searchFilter (based on the keyword model) works on the scope as intended.
However, when I click the cityFilter() button, the controller does get new data (if I do console.log($scope.jobs) inside my cityFilter() function, I see the intended JSON object in my console) but the view does not reflect these changes.
Why does the view reflect the changes in the keyword model, but not the cityFilter() changes? If the scope is different, as I first thought, shouldn't both be ineffective?
I set it up this way because I want the sidebar to be accessible from anywhere in the application. I am mostly confused by the fact that my controller seems to be aware of the changes to $scope variables but doesn't 'transmit' them to the view, even though ng-click is inside an $apply according to Angular documentation. Any idea of what I'm doing wrong?
EDIT: The way my initial template is loaded using routeProvider:
angular.module('someModule', ['ngRoute']).config(['$routeProvider', '$locationProvider',
function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'dir/views/job-posting.html',
controller: 'JobPostingsCtrl'
})
...
The HTML for the template:
<div ng-repeat="job in jobs | filter:searchFilter>
{{ job.someProperty }}
</div>
The index.html:
<div ng-controller="MasterCtrl">
<div id="sidebar" ng-controller="JobPostingsCtrl">
<input type="search" name="search" id="search" ng-model="keyword">
<input type="search" name="location" id="location" ng-model="locationFilter">
<button id="go" ng-click="cityFilter();">Click</button>
</div>
<div ng-view></div>
</div>
I've been following a course to learn angularjs and I can't seem to get a simple ng-click binding to work.
HTML:
<body ng-controller="MainController">
<div ng-app="githubViewer">
<h1>{{message}}</h1>
<div>{{ error }}</div>
{{username}}
<form name="searchUser">
<input type="search" placeholder="Username to find" ng-model="username" />
<input type="submit" value="Search" ng-click="search(username)" />
</form>
<div>
<div>{{user.name}}</div>
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}" title="{{user.name}}">
{{user.gravatar_id}}
</div>
</div>
</body>
Javascript:
(function () {
var module = angular.module("githubViewer", []);
var MainController = function ($scope, $http) {
var onUserComplete = function (response) {
$scope.user = response.data;
};
var onError = function (reason) {
$scope.error = "Could not fetch the user";
$scope.reason = reason;
};
$scope.username = "angular";
$scope.message = "Github Viewer";
$scope.search = function (username) {
$http.get("https://api.github.com/users/" + username)
.then(onUserComplete, onError);
};
};
module.controller("MainController", MainController);
}());
When you click the search button (search for username "odetocode" or "robconery") it is supposed to display an image but the click event does not seem to be firing. I have searched the documentation and looked over the course again but I can't see what I'm doing wrong.
I'm currently using version 1.2.16 of angularjs.
You have the ng-controller declaration outside of the ng-app declaration right now:
<body ng-controller="MainController">
<div ng-app="githubViewer">
It should be the other way around, or have both on the same element
<body ng-app="githubViewer" ng-controller="MainController">
<div>
AngularJS evaluates your code, and checks for any directives you have declared from the ng-app element down, including the element it is declared on; This currently is missing the ng-controller directive, as it is placed on a parent element of the ng-app element.
You need to put the controller within the context of the module to have it within its scope.
Like so
<body ng-app="githubViewer" ng-controller="MainController">
Demo here
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
Here is the jsfiddle.
http://jsfiddle.net/CLcfC/
code
var app = angular.module('app',['']);
app.controller('TestCtrl',function($scope){
$scope.text = 'Change Me';
$scope.$watch('text',function(){
alert('Changed !');
});
})
HTML
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="TestCtrl">
<input type="text" ng-model='text'/>
<span>{{text}}</span>
</div>
</div>
I am not able to see the change in $scope.text. Please help.
This is so easy but what am I missing?
Change the module creation to this, make sure you don't put a empty string in the []. (Obvious the empty string is not a module that can be injected.)
var app = angular.module('app', []);
Demo: http://jsfiddle.net/MWa66/
Your JavaScript file loads after the AngularJS initialization and that's why it fails to find your module. In order to fix it change the initialization to a manual initialization.
First change your HTML and remove the ng-app directive:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div id="appRoot">
<div ng-controller="TestCtrl">
<input type="text" ng-model='text'/>
<span>{{text}}</span>
</div>
</div>
Then go to your JavaScript and use angular.bootstrap method to manually attach your module:
var app = angular.module('app',[]);
app.controller('TestCtrl',function($scope){
$scope.text = 'Change Me';
$scope.$watch('text',function(){
alert('Changed !');
});
});
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById('appRoot'), ['app']);
});
You can find more help on manual AngularJS initialization here.
Thank you! I solved this annoying thing!
The solution that worked for me was that I use angular UI router and there I had used the following code
.state('app.monimes', {
url: "/monimes",
views: {
'menuContent' :{
templateUrl: "templates/monimes.html",
controller: 'sampleCtrl'
}
}
})
so then in the controller I had
/***
*
*Controller for tests..
*/
.controller('sampleCtrl',['$scope','sampleService', function($scope, $sampleService) {
$scope.username="em";
// Watch for changes on the username property.
// If there is a change, run the function
$scope.$watch('username', function(newUsername) {
// uses the $http service to call the GitHub API
// //log it
$scope.log(newUsername);
// and returns the resulting promise
$sampleService.events(newUsername)
.success(function(data, status, headers) {
// the success function wraps the response in data
// so we need to call data.data to fetch the raw data
$scope.events = data.data;
});
},true);
}
]);
and in the view I had
<div>
<label for="username">Type in a GitHub username</label>
<input type="text" ng-model="username" placeholder="Enter a GitHub username, like a user" />
<pre ng-show="username">{{ events }}</pre>
</div>
but that didn't work.
so I added ng-controller="sampleCtrl"
to the div and now it works :D
so that means that the view is loaded after the controller loads and the watcher doesn't get added to the watching variable.