I have modal code (below) wrapped in nav.html and it works as expected (login, logout...works).
<div class="modal fade" id="authModal" role="dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<form class="form-signin" role="form">
<input ng-model="user.email" type="email" class="form-control" placeholder="Email address" required="" autofocus="">
<input ng-model="user.password" type="password" class="form-control" placeholder="Password" required="">
<div class="checkbox checkbox-success">
<input ng-model="checkbox.signup" ng-init="checkbox.signup=false" type="checkbox">
<label> Sign Up for first-timer </label>
</div>
<div class="text-center">
<button ng-click="login($event)" class="btn btn-lg btn-primary" type="button">Sign In</button>
</div>
</form>
</div>
</div>
But when I move all modal content to a file named md.html and include it to nav.html via
<div class="navbar-header" ng-controller="MainCtrl">
<div ng-include="'views/modals/md.html'"></div>
</div>
It is absolute that I have it included in the ng-controller div.
On testing, I got error of unable to reference to user.password for the Controller. The controller works fine previously and I didn't change anything on it. For this question, I m posting a simplified version of modal and controller code.
$scope.login = function($event){ $event.preventDefault();
// console.log("cond ", cond, ".checkbox.signup ", $scope.checkbox.signup);
if (!$scope.logged)
fn.login($scope.user, function(){
if ($scope.checkbox.signup) fn.signup($scope.user);
});
};
var fn = {
login: function(user, cb){
if (Auth.authData) return;
if (!user.password) {
fn.alert("please type password");
return;
}
if (fn.valid_email(user.email))
Auth.ref_ds1.authWithPassword(user, function(error, authData) {
if (error) {
fn.alert(error);
cb();
} else {
authData.email = $scope.user.email;
console.log("Authenticated successfully on:", authData.email);
fn.greet("Hello " + authData.email.split("#")[0]);
$scope.logged = true;
window.location.href = "/";
}
});
}
}
How to reference them correctly?
It looks like you could be seeing issues with your ng-include creating another scope and you're not able to reference the previously defined user object.
One way I avoid confusion with scopes is using "Controller as" syntax to reference a scope specifically (see http://www.johnpapa.net/angularjss-controller-as-and-the-vm-variable/). Here's a tiny example:
// in the controller
app.controller('MainController', function() {
var vm = this;
this.somevalue = 'something';
})
// markup
<div ng-controller="MainCtrl as ctrl">
{{ ctrl.somevalue }}
<div ng-controller="SecondCtrl as secondCtrl">
{{ ctrl.somevalue }}
{{ secondCtrl.anothervalue }}
</div>
</div>
Using "Controller as" will really help unwind scope problems you're having, but it would take some re-tooling of your original controller.
Related
Here is my todo.js file
//let example = angular.module("example", ["ngStorage"]);
example.controller("ExampleController", function($scope, $localStorage) {
$scope.save = function() {
let testObject = [
{
name:"aaa",
lastName:"bbb"
},
{
name:"ccc",
lastName:"ddd"
}
]
let myVal = $localStorage.myKey;
$localStorage.$reset();
if(!myVal){
console.log("okey");
$localStorage.myKey = testObject;
} else {
myVal.push({
name:"fff",
lastName:"ggg"
})
$localStorage.myKey = myVal;
}
$scope.datas = $localStorage.myKey;
}
$scope.load = function() {
console.log($localStorage.myKey)
}
});*/
var app = angular.module("modalFormApp", ['ui.bootstrap']);
app.controller("modalAccountFormController", function ($scope, $modal, $log) {
$scope.showForm = function () {
$scope.message = "Show Form Button Clicked";
console.log($scope.message);
var modalInstance = $modal.open({
templateUrl: 'modal.html',
controller: ModalInstanceCtrl,
scope: $scope,
resolve: {
userForm: function () {
return $scope.userForm;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
var ModalInstanceCtrl = function ($scope, $modalInstance, userForm) {
$scope.form = {}
$scope.submitForm = function () {
if ($scope.form.userForm.$valid) {
console.log('user form is in scope');
$modalInstance.close('closed');
} else {
console.log('userform is not in scope');
}
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
And here is my index.html file:
<html>
<head>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="../node_modules/angular-1.6.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.10/ngStorage.min.js"></script>
<script src="./todo.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.9.0.js"></script>
</head>
<body>
<!--<div ng-app="example">
<div ng-controller="ExampleController">
<button ng-click="save()">Save</button>
<button ng-click="load()">Load</button>
<br>
<input type='text' ng-model='searchText' placeholder="Search..." />
<ul>
<li ng-repeat="data in datas | filter:searchText">
{{data.name}}
</li>
</ul>
</div>
</div>-->
<div ng-app="modalFormApp">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
<!-- PAGE HEADER -->
<div class="page-header">
<h1>AngularJS Form Validation</h1>
</div>
<div ng-controller="modalAccountFormController">
<div class="page-body">
<button class="btn btn-primary" ng-click="showForm()">Create Account</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Lastly here is my modal.html:
<div class="modal-header">
<h3>Create A New Account!</h3>
</div>
<form name="form.userForm" ng-submit="submitForm()" novalidate>
<div class="modal-body">
<!-- NAME -->
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-model="name" required>
<p ng-show="form.userForm.name.$invalid && !form.userForm.name.$pristine" class="help-block">You name is required.</p>
</div>
<!-- USERNAME -->
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8" required>
<p ng-show="form.userForm.username.$error.minlength" class="help-block">Username is too short.</p>
<p ng-show="form.userForm.username.$error.maxlength" class="help-block">Username is too long.</p>
</div>
<!-- EMAIL -->
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-model="email" required>
<p ng-show="form.userForm.email.$invalid && !form.userForm.email.$pristine" class="help-block">Enter a valid email.</p>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" ng-disabled="form.userForm.$invalid">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</form>
I'm trying to open a modal when i click the button. I made comment line the other part which i'm using but it works fine. The second part is for only the modal but it is not working. I even can not open the modal. If there is a basic way to do this can you share with me? I only need to open this modal. I can handle the rest of it.
From the Docs:
There are a few things to keep in mind when using ngApp:
only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead.
For more information, see
AngularJS ng-app Directive API Reference
I am building a website and i wish to make a single page application. Iam using nodejs as a backend and angular as a frontend. The thing iam stuck up is i want to show a particular div when user is not logged in, on the event of logging in the other div should be shown. What is the best way to make it happen.
As per my knowledge i have used ng-if as the attribute of both the div which i want to replace each other. I had a angular function for verifying the logged in sesssion with a name isloggedin().
so i used <div ng-if="!checkLoggedin()"> in one div and <div ng-if="checkLoggedin()"> in other div.
So on the first request the page is not logged in and the conditions works as it should. But after i logged in the from the second is not showing up.
Is it something i wrongly expect to happen or is there any other to make this happen. I had check the value of the function and it has data in one condition and 0 in other condition. Am i wrong somewhere.
Added the conditional code.
var checkLoggedin = function ($q, $timeout, $http, $location, $rootScope) {
var deferred = $q.defer();
$http({
method: 'GET',
url: "http://localhost:3000/loggedin"
}).success(function (user) {
if (user !== '0') {
$rootScope.message = 'You are log in.';
$timeout(deferred.resolve, 0);
deferred.resolve();
$location.url('/home');
} else {
$rootScope.message = 'You need to log in.';
$timeout(function () {
deferred.reject();
}, 0);
deferred.reject();
$location.url('/login');
};
});
Here is the form code.
<form action="/#/home" ng-submit="login(user)">
<div class="form-group">
<div class="input-group input-group-in ui-no-corner no-border bordered-bottom bg-none">
<div class="input-group-addon"><i class="fa fa-envelope text-muted"></i></div>
<input class="form-control" placeholder="email" ng-model="user.email">
</div>
</div><!-- /.form-group -->
<div class="form-group">
<div class="input-group input-group-in ui-no-corner no-border bordered-bottom bg-none">
<div class="input-group-addon"><i class="fa fa-lock text-muted"></i></div>
<input type="password" class="form-control" placeholder="Password" ng-model="user.password">
<div class="input-group-addon"><small>Forgot?</small></div>
</div>
</div><!-- /.form-group -->
<div class="form-group">
<div class="row">
<div class="col-md-6">
<div class="nice-checkbox nice-checkbox-inline">
<input type="checkbox" name="rememberSignIn1" id="rememberSignIn">
<label for="rememberSignIn1">Remember</label>
</div>
</div><!-- /.cols -->
<div class="col-md-6">
<button type="submit" class="btn btn-sm btn-block btn-info" style="margin-top:5px" >SUBMIT</button>
</div><!-- /.cols -->
</div><!-- /.row -->
</div><!-- /.form-group -->
</form><!-- /form -->
</div><!-- /.panel-body -->
As I see, the blocks
<div ng-if="!checkLoggedin()">
and
<div ng-if="checkLoggedin()">
will be executed on DOM load (page load). So there is no chance for the model to update. The right approach here will be to use a scope variable in the if blocks as
<div ng-if="isLoggedIn"> ... <div ng-if="!isLoggedIn">
and to update the variable's value in the success handler of the service call, say,
var checkLoggedin = function ($q, $timeout, $http, $location, $rootScope) {
var deferred = $q.defer();
$http({
method: 'GET',
url: "http://localhost:3000/loggedin"
}).success(function (user) {
if (user !== '0') {
// set value here
$rootScope.isLoggedIn = true;
$rootScope.message = 'You are log in.';
$timeout(deferred.resolve, 0);
deferred.resolve();
$location.url('/home');
} else {
$rootScope.message = 'You need to log in.';
$timeout(function () {
deferred.reject();
}, 0);
deferred.reject();
$location.url('/login');
};
});
This way we can be sure that the model has updated values and the right if block will be added to DOM.
Your approach is correct, but may be you have not defined checkLoggedin() properly or may be you used in wrong way.
You can approach it with different way also,
Apply ng-if condition on ng-model variable,
<label> User Name </label>
<input ng-model="username" />
So here you can add condition on username, like:-
<div ng-if="username !== 'null' || 'undefined'"> If username fielld is touched </div>
<div ng-if="username === 'null' || 'undefined'"> If username field is not touched </div>
so I have a form with an input and some other stuff and I'm trying to do some angular validation to make sure that the entered information is actually there (not blank). To do so, I'm using an if statement.
The error message I get is:
Cannot read property 'name' of undefined
It seems as if it can't read an <input> tag name if it's left blank. The function works when I fill in the , but not the others (which are a and . I'm just trying to use an if statement to see if they've been filled out. Here's the html and angular code below:
reviewModal.view.html (shortened form version)
<div class="modal-content">
<div role="alert" ng-show="vm.formError" class="alert alert-danger">{{ vm.formError }}</div>
<form id="addReview" name="addReview" role="form" ng-submit="vm.onSubmit()" class="form-horizontal">
<label for"name" class="col-xs-2 col-sm-2 control-label">Name</label>
<div class="col-xs-10 col-sm-10">
<input id="name" name="name" ng-model="vm.formData.name" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Submit review</button>
</form>
</div>
reviewModal.controller.js
(function() {
angular
.module('loc8rApp')
.controller('reviewModalCtrl', reviewModalCtrl);
reviewModalCtrl.$inject = ['$uibModalInstance', 'locationData'];
function reviewModalCtrl($uibModalInstance, locationData) {
var vm = this;
vm.locationData = locationData;
vm.onSubmit = function() {
vm.formError = "";
if(!vm.formData.name || !vm.formData.rating || !vm.formData.reviewText) {
vm.formError = "All fields required, please try again";
return false;
} else {
console.log(vm.formData);
return false;
}
};
vm.modal = {
cancel : function() {
$uibModalInstance.dismiss('cancel');
}
};
}
})();
locationDetail.controller.js
(function() {
angular
.module('loc8rApp')
.controller('locationDetailCtrl', locationDetailCtrl);
locationDetailCtrl.$inject = ['$routeParams', '$uibModal', 'loc8rData'];
function locationDetailCtrl($routeParams, $uibModal, loc8rData) {
var vm = this;
vm.locationid = $routeParams.locationid;
loc8rData.locationById(vm.locationid)
.success(function(data) {
vm.data = { location: data };
vm.pageHeader = {
title: vm.data.location.name
};
})
.error(function(e) {
console.log(e);
});
vm.popupReviewForm = function() {
var modalInstance = $uibModal.open({
templateUrl: '/reviewModal/reviewModal.view.html',
controller: 'reviewModalCtrl as vm',
resolve : {
locationData : function() {
return {
locationid : vm.locationid,
locationName : vm.data.location.name
};
}
}
});
};
}
})();
vm.formData must be defined before you can assigned/read name property in the html. Update code in reviewModalCtrl to init vm.formData:
vm.formData = {};
Use angular validation instated validating things in controller as follows.
<div class="modal-content">
<div role="alert" ng-show="addReview.$submitted && addReview.$invalid" class="alert alert-danger">All fields required, please try again</div>
<form id="addReview" name="addReview" role="form" ng-submit="vm.onSubmit()" class="form-horizontal">
<label for"name" class="col-xs-2 col-sm-2 control-label">Name</label>
<div class="col-xs-10 col-sm-10">
<input id="name" name="name" ng-model="vm.formData.name" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary">Submit review</button>
</form>
</div>
I have used required in text box and show the error message on top with
ng-show="addReview.$invalid"
You do not need any code on controller.
I am trying nodeJS, SailsJS & Angular. I want use this loading bar:
http://chieffancypants.github.io/angular-loading-bar/
https://github.com/chieffancypants/angular-loading-bar
I read the loading bar handle http request are automatically.
so i do this :
npm install angular-loading-bar.
I put the jss and css in assets.
Here my LoginModule :
var LoginModule = angular.module('LoginModule', ['angular-loading-bar']);
And my LoginController :
angular.module('LoginModule')
.controller('LoginController', LoginController);
LoginController.$inject = ['$scope', '$http', 'cfpLoadingBar'];
function LoginController($scope, $http, cfpLoadingBar) {
// Get CSRF token and set as header
$http.defaults.headers.post['X-CSRF-Token'] = document.getElementsByName('_csrf')[0].value;
$scope.submitLoginForm = function() {
$scope.start();
$http.post('/login', {
identifiant: $scope.login.identifiant,
password: $scope.login.password
})
.then(function onSuccess() {
window.location = '/home/';
})
.catch(function onError(response) {
console.log(response);
})
}
$scope.start = function() {
cfpLoadingBar.start();
};
$scope.complete = function() {
cfpLoadingBar.complete();
};
}
But when i login on my form :
<div class="container-fluid" ng-app="LoginModule" ng-controller="LoginController" ng-cloak>
<div class=" col-lg-offset-4 col-lg-4">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Connexion</h3>
</div>
<div class="panel-body">
<h5 class="col-lg-12" style="text-align: center">Admin !</h5>
<form ng-submit="submitLoginForm()" class="col-lg-offset-3 col-lg-6 form-group" name="loginForm">
<input type="text" class="form-control" id="inputLogin" name="inputLogin" placeholder="Identifiant" ng-model="login.identifiant">
<input type="password" class="form-control" id="inputPassword" name="inputPassword" placeholder="Mot de passe" ng-model="login.password">
<br>
<button type="submit" class="btn btn-primary" style="float: right">Connexion</button>
<input type="hidden" name="_csrf" value="<%= _csrf %>">
</form>
</div>
</div>
</div>
</div>
I don't see the loading bar when i submit the form (form working) :( why ? Also when i try to load ngAnimate in LoginModule i have an error
I tried also the function start() on element HTML but nothing..
You Must include angular-animate.min.js to make it work
as also include in git repository example. when I removed this line
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-animate.min.js"></script>
it stopped working please make sure you include animation file. that's why ngAnimate also giving error
I have save method on modal window once user execute save method i want to clear the form fields, I have implemented $setPristine after save but its not clearing the form. How to achieve that task using angularJS ?
So far tried code....
main.html
<div>
<form name="addRiskForm" novalidate ng-controller="TopRiskCtrl" class="border-box-sizing">
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="topRiskName" class="required col-md-4">Top Risk Name:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="topRiskName" ng-model="topRiskDTO.topRiskName"
name="topRiskName" required>
<p class="text-danger" ng-show="addRiskForm.topRiskName.$touched && addRiskForm.topRiskName.$error.required">Top risk Name is required field</p>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="issuePltfLookUpCode" class="col-md-4">Corresponing Issue Platform:</label>
<div class="col-md-8">
<select
kendo-drop-down-list
data-text-field="'text'"
data-value-field="'id'" name="issuePltfLookUpCode"
k-option-label="'Select'"
ng-model="topRiskDTO.issuePltfLookUpCode"
k-data-source="issuePltDataSource"
id="issuePltfLookUpCode">
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="issueNo" class="col-md-4">Issue/Risk Number:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="issueNo" ng-model="topRiskDTO.issueNo"
name="issueNo">
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary pull-right" ng-disabled="addRiskForm.$invalid" ng-click="submit()">Save</button>
<button class="btn btn-primary pull-right" ng-click="handleCancel">Cancel</button>
</div>
</form>
</div>
main.js
$scope.$on('addTopRisk', function (s,id){
$scope.riskAssessmentDTO.riskAssessmentKey = id;
$scope.viewTopRiskWin.open().center();
$scope.submit = function(){
rcsaAssessmentFactory.saveTopRisk($scope.topRiskDTO,id).then(function(){
$scope.viewTopRiskWin.close();
$scope.$emit('refreshTopRiskGrid');
$scope.addRiskForm.$setPristine();
});
};
});
Hey interesting question and I have messed around with it and I have come up with something like this (I have abstracted the problem and simplified it, it is up to you to implent it to your likings). Likely not super elegant but it does the job: Fiddle
<div ng-app="app">
<div ng-controller="main">
<form id="form">
<input type="text" />
<input type="text" />
</form>
<button ng-click="clear()">clear</button>
</div>
</div>
JS
angular.module("app", [])
.controller("main", function ($scope) {
$scope.clear = function () {
var inputs = angular.element(document.querySelector('#form')).children();
angular.forEach(inputs, function (value) {
value.value="";
});
};
})
Hope it helps.
Edit
If you give all your inputs that must be cleared a shared class you can select them with the querySelector and erase the fields.
Refer to this page: http://blog.hugeaim.com/2013/04/07/clearing-a-form-with-angularjs/
$setPristine will only clear the variables not the form. To clear the form set their values to blank strings
<script type="text/javascript">
function CommentController($scope) {
var defaultForm = {
author : "",
email : "",
comment: ""
};
$scope.postComments = function(comment){
//make the record pristine
$scope.commentForm.$setPristine();
$scope.comment = defaultForm;
};
}
</script>
Clear topRiskDTO
Looking at your example, seems that clearing topRiskDTO will give you this result.
for instance:
$scope.submit = function(){
// ...
// The submit logic
// When done, Clear topRiskDTO object
for (var key in $scope.topRiskDTO)
{
delete $scope.topRiskDTO[key];
}
};
You have to manually reset the data. See this website for more info.
You also have to call
$form.$setPristine()
To clear all the css classes.