I'm trying to setup some controllers in my angular app but I'm not sure why I can't make them working, since I think I'm using similar approach as I've done before.
I declared app.js file:
'use strict';
var modules = [
'app.controllers',
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ui.router',
'LocalStorageModule',
'angular-loading-bar'
];
var app = angular.module('app', modules);
app.config(function($httpProvider) {
$httpProvider.interceptors.push('authInterceptorService');
})
app.factory('forgotPasswordService', ['$http', function ($http) {
var fac = {};
fac.forgotPassword = function (forgotPasswordData) {
return $http.post('/api/Account/ForgotPassword', forgotPasswordData)
};
return fac;
}])
app.factory('signUpService', ['$http', function ($http) {
var signUpServiceFactory = {};
signUpServiceFactory.saveRegistration = function (registration) {
return $http.post('/api/account/register', registration);
};
return signUpServiceFactory;
}]);
Then controllers.js file with this content:
angular.module('app.controllers', [])
.controller('signupController', [
'$scope', '$window', 'signUpService',
function($scope, $window, signUpService) {
$scope.init = function() {
$scope.isProcessing = false;
$scope.RegisterBtnText = "Register";
};
$scope.init();
$scope.IsLimitedCompany = null;
$scope.registration = {
Email: "",
Password: "",
ConfirmPassword: ""
};
$scope.signUp = function() {
$scope.isProcessing = true;
$scope.RegisterBtnText = "Please wait...";
signUpService.saveRegistration($scope.registration).then(function(response) {
alert("Registration Successfully Completed. Please sign in to Continue.");
$window.location.href = "login.html";
}, function() {
alert("Error occured. Please try again.");
$scope.isProcessing = false;
$scope.RegisterBtnText = "Register";
});
};
}
]);
And my html file:
<!DOCTYPE html>
<!--[if !IE]><!-->
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<script src="/Metronic/plugins/jquery.min.js" type="text/javascript"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="/Scripts/angular.js"></script>
<script src="/Scripts/angular-cookies.min.js"></script>
<script src="/Scripts/angular-resource.min.js"></script>
<script src="/Scripts/angular-sanitize.min.js"></script>
<script src="/Scripts/angular-route.min.js"></script>
<script src="/Scripts/angular-ui-router.min.js"></script>
<script src="/Angular/app.js"></script>
<script src="/Angular/controllers.js"></script>
<script src="/Scripts/angular-local-storage.min.js"></script>
<script src="/Scripts/loading-bar.min.js"></script>
<script src="/Angular/Services/authInterceptorService.js"></script>
</head>
<body class="login">
<div class="content" ng-app="app">
<!-- BEGIN REGISTRATION FORM -->
<div class="register-form" ng-controller="signupController">
<h3 class="font-green">Sign Up</h3>
<p class="hint"> Enter your account details below: </p>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Email</label>
<input class="form-control placeholder-no-fix" ng-model="registration.Email" type="text" autocomplete="off" placeholder="Email" name="username" />
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<input class="form-control placeholder-no-fix" ng-model="registration.Password" type="password" autocomplete="off" id="register_password" placeholder="Password" name="password" />
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Re-type Your Password</label>
<input class="form-control placeholder-no-fix" ng-model="registration.ConfirmPassword" type="password" autocomplete="off" placeholder="Re-type Your Password" name="rpassword" />
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Role</label>
<select name="role" ng-change="CheckRole()" ng-model="registration.Role" class="form-control">
<option value="">Role</option>
<option value="Borrower">Borrower</option>
<option value="Introducer">Introducer</option>
<option value="Investor">Investor</option>
<option value="Valuer">Valuer</option>
</select>
</div>
<div class="form-actions">
<button type="button" id="register-back-btn" class="btn green btn-outline">Back</button>
<button type="submit" id="register-submit-btn" class="btn btn-success uppercase pull-right" ng-click="signUp()" ng-disabled="isProcessing" value="{{RegisterBtnText}}">
Submit
</button>
</div>
</div>
<!-- END REGISTRATION FORM -->
</div>
</body>
</html>
Any idea what am I missing?
I'm getting this error:
Error: [ng:areq] Argument 'signupController' is not a function, got undefined
You have included JS file in wrong order.
Currently it is
<script src="/Angular/app.js"></script>
<script src="/Angular/controllers.js"></script>
Because of this your app.js not getting the defination of app.controllers.
Its should be like this one
<script src="/Angular/controllers.js"></script>
<script src="/Angular/app.js"></script>
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
My idea is to create a big form from separated components. So this is my main template:
<form novalidate>
<div class="row">
<user></user>
</div>
<button type="button" class="btn btn-default" ng-click="submit()"> Submit </button>
</form>
and its controller (the template is binded from ui route config to the controller)
(function () {
'use strict';
angular.module('app')
.controller('formCtrl', formCtrl);
function formCtrl ($scope) {
$scope.submit = function() {
console.log("read data");
}
}
})();
Now, the user component:
(function () {
'use strict';
var module = angular.module('app.user');
module.component("user", {
templateUrl: "app/user/user.html",
controllerAs: "model",
controller: function () {
var model = this;
model.user = {};
}
});
})();
and the user template:
<form novalidate>
<form-group>
<label for="inputUser"> Name <label>
<input ng-model="model.user.name" id="inputUser" type="text" placeholder="User"/>
</form-group>
<form-group>
<label for="inputUser"> Email <label>
<input ng-model="model.user.email" id="inputUser" type="email" placeholder="Email"/>
</form-group>
<div>
{{model.user | json}}
</div>
</form>
Now I want to be able to read user data when the user do the submit. How can I do it?
When using components, depending on the type of component (smart or dumb), you have to emit an output to the parent controller to handle such thing. But in this case, you can use ngModel to handle a model and change it on the parent from within the component. For example:
Working snippet:
angular.module('app', [])
.controller('formCtrl', function($scope) {
$scope.user = {};
$scope.submit = function() {
console.log($scope.user);
}
})
.component("user", {
bindings: {
user: '=ngModel'
},
templateUrl: "app/user/user.html",
controllerAs: "model",
controller: function() {}
});
angular.element(function() {
angular.bootstrap(document, ['app']);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<form novalidate ng-controller="formCtrl">
<div class="row">
<user ng-model="user"></user>
</div>
<button type="button" class="btn btn-default" ng-click="submit()">Submit</button>
</form>
<script type="text/ng-template" id="app/user/user.html">
<form novalidate>
<div>
<label for="inputUser">Name
<label>
<input ng-model="model.user.name" id="inputUser" type="text" placeholder="User" />
</div>
<div>
<label for="inputUser">Email
<label>
<input ng-model="model.user.email" id="inputUser" type="email" placeholder="Email" />
</div>
<div>
{{ model.user | json }}
</div>
</form>
</script>
A possible solution would be $$childTail. So if I want to access to user:
$scope.$$childTail.model.user
I am work on my personal project for practice angularJS but I met a unsolvable problem for me.
I wanted to use submitLogin() function in LoginCtrl.js when I submit the form but error console in Safari browser says that $scope.submitLogin is readonly property, so that I can't figure out what's wrong.
How can I solve the readonly property error? and What caused this error?
I got error as below :
Error: Attempted to assign to readonly property.
http://localhost:8080/js/controllers/LoginCtrl.js:6:13
[native code]
instantiate#http://localhost:8080/libs/angular/angular.js:4723:61
$controller#http://localhost:8080/libs/angular/angular.js:10192:39
link#http://localhost:8080/libs/angular-route/angular-route.js:1017:37
http://localhost:8080/libs/angular/angular.js:1266:23
invokeLinkFn#http://localhost:8080/libs/angular/angular.js:9757:15
nodeLinkFn#http://localhost:8080/libs/angular/angular.js:9156:23
compositeLinkFn#http://localhost:8080/libs/angular/angular.js:8459:23
publicLinkFn#http://localhost:8080/libs/angular/angular.js:8339:45
lazyCompilation#http://localhost:8080/libs/angular/angular.js:8677:30
boundTranscludeFn#http://localhost:8080/libs/angular/angular.js:8476:28
controllersBoundTransclude#http://localhost:8080/libs/angular/angular.js:9206:37
update#http://localhost:8080/libs/angular-route/angular-route.js:975:36
$broadcast#http://localhost:8080/libs/angular/angular.js:17701:33
http://localhost:8080/libs/angular-route/angular-route.js:615:36
processQueue#http://localhost:8080/libs/angular/angular.js:16104:30
http://localhost:8080/libs/angular/angular.js:16120:39
$eval#http://localhost:8080/libs/angular/angular.js:17378:28
$digest#http://localhost:8080/libs/angular/angular.js:17191:36
$apply#http://localhost:8080/libs/angular/angular.js:17486:31
done#http://localhost:8080/libs/angular/angular.js:11637:53
completeRequest#http://localhost:8080/libs/angular/angular.js:11843:15
requestLoaded#http://localhost:8080/libs/angular/angular.js:11776:24 – "<div ng-view=\"\" class=\"ng-scope\">"
index.html(only javascript included part)
...
<!-- JS -->
<script src="libs/angular/angular.js"></script>
<script src="libs/angular-route/angular-route.js"></script>
<script src="libs/angular-cookies/angular-cookies.js"></script>
<!-- ANGULAR COMSTOM -->
<script src="js/controllers/MainCtrl.js"></script>
<script src="js/controllers/NerdCtrl.js"></script>
<script src="js/controllers/LoginCtrl.js"></script>
<script src="js/services/NerdService.js"></script>
<script src="js/services/ReviewService.js"></script>
<script src="js/services/LoginService.js"></script>
<script src="js/appRoutes.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="sampleApp">
...
appRoutes.js // controller in charge of routing
angular.module('appRoutes', []).
config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'MainController'
})
.when('/login', {
templateUrl: 'views/login.html',
controller: 'LoginController'
});
$locationProvider.html5Mode(true);
}]);
login.html
<div class = "row" >
<div class= "col-md-4 col-md-offset-4">
<h3 class = "text-center">LOGIN</h3>
<form ng-submit="submitLogin()"> // <-
<div class = "form-group">
<div class="input-group">
<span class = "input-group-addon">
<i class="fa fa-envelope-o"></i>
</span>
<input id = "login_email" type="text" name="name" class="form-control input-lg" placeholder="Email"
ng-model="login.email" required>
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-asterisk" aria-hidden="true"></i>
</span>
<input id="login_password" type="password" name="password" class="form-control input-lg"
placeholder="Password" ng-model="login.password" required>
</div>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block btn-shadow">Login</button>
</form>
</div>
</div>
LoginCtrl.js
'use strict';
angular.module('LoginCtrl', ['LoginService', 'ngCookies'])
.controller('LoginController', [
function($scope, Login, $cookieStore) {
$scope.submitLogin = function() {
Login.getToken($scope.login.email, $scope.login.password)
.then(function(response) {
if(response.data['success'] == true) {
$scope.token = response.data['token'];
$cookieStore.put('Token', $scope.token);
//$window.alert($cookieStore.get('Token'));
}
else {
$scope.token = null;
}
})};
}]);
LoginService.js
angular.module('LoginService', []).factory('Login', ['$http', function($http) {
return {
getToken : function(name, password) {
var data = { name: name, password: password}
$http.get('/authenticate', data);
},
getAllUsers: function(token) {
$http.get('/users')
}
}
}])
The problem was I didn't return $http.get in LoginService.js that was why Login.getToken() was not an object
I am trying to implement a simple Angular file upload. I am already having a controller for that particular page as shown below:
app.controller('PageCtrl', function ($scope, $rootScope, $location, $routeParams, services, video) {
var videoID = ($routeParams.videoID) ? parseInt($routeParams.videoID) : 0;
var original = video.data;
original._id = videoID;
$scope.video = angular.copy(original);
$scope.video._id = videoID;
$scope.isClean = function() {
return angular.equals(original, $scope.video);
}
// Activates the Carousel
$('.carousel').carousel({
interval: 5000
});
// Activates Tooltips for Social Links
$('.tooltip-social').tooltip({
selector: "a[data-toggle=tooltip]"
})
});
My HTML looks like this
<div class="form-group">
<label class="col-md-4 control-label" for="Message">Message</label>
<div class="col-md-4">
<textarea class="form-control" id="Message" name="Message">Hi David...</textarea>
</div>
</div>
<!-- Multiple Checkboxes -->
<div class="form-group">
<label class="col-md-4 control-label" for=""></label>
<div class="col-md-4">
<div class="checkbox">
<label for="-0">
<input ng-model="imagesModal" type="checkbox" name="" id="-0" value="1">
Upload Images
</label>
</div>
</div>
</div>
<!--Images Form Group-->
<div class="form-group" ng-show="imagesModal">
<input type="file" ng-file-select="onFileSelect($files)" >
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="Submit"></label>
<div class="col-md-4">
<button id="Submit" name="Submit" class="btn btn-primary">Submit</button>
</div>
</div>
I am trying to include Angular file upload controller as shown in the answer. I tried
app.controller('PageCtrl', ['$scope', '$upload', function ($scope, $rootScope, $location, $routeParams, services, video) {
var videoID = ($routeParams.videoID) ? parseInt($routeParams.videoID) : 0;
var original = video.data;
original._id = videoID;
$scope.video = angular.copy(original);
$scope.video._id = videoID;
$scope.isClean = function() {
return angular.equals(original, $scope.video);
}
$scope.onFileSelect = function($files) {
var file = $files[0];
if (file.type.indexOf('image') == -1) {
$scope.error = 'image extension not allowed, please choose a JPEG or PNG file.';
}
if (file.size > 2097152){
$scope.error ='File size cannot exceed 2 MB';
}
$scope.upload = $upload.upload({
url: upload.php,
data: {fname: $scope.fname},
file: file,
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
};
// Activates the Carousel
$('.carousel').carousel({
interval: 5000
});
// Activates Tooltips for Social Links
$('.tooltip-social').tooltip({
selector: "a[data-toggle=tooltip]"
})
}]);
I am getting . I tried declaring all the parameters too
app.controller('PageCtrl', ['$scope', '$upload', '$rootScope', '$location', '$routeParams', function ($scope, $rootScope, $location, $routeParams, services, video) {
But still the same error. So I removed all the declaration too. No use.
I have been struggling with it for the long time now. I am just starting with angular. No clue where I am wrong.
UPDATE:
var app = angular.module('videomandiApp', [
'ngRoute','youtube-embed','ngFileUpload'
]);
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="js/ng-file-upload.min.js"></script>
<script src="js/ng-file-upload-shim.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
<script src="https://www.youtube.com/iframe_api"></script>
<script src="http://brandly.github.io/angular-youtube-embed/angular-youtube-embed.js"></script>
<script src="js/main.js"></script>
I can't seem to find why the "start" and "finish" part of my form isn't being rendered. This is the first time I've ever worked with AngularJS, and after following quite a few tuts online, I used to yo meanjs generator with the articles example. I then took the articles example and tried to port it over to this scheduling thing. It really doesn't matter though, I just want to know why the last two inputs in the form aren't being rendered in my view.
Any help is much appreciated
Here's the code for my view:
<section data-ng-controller="SchedulesController">
<div class="page-header">
<h1>New Schedule</h1>
</div>
<div class="col-md-12">
<form name="scheduleForm" class="form-horizontal" data-ng-submit="create()" novalidate>
<fieldset>
<div class="form-group" ng-class="{ "has-error": scheduleForm.title.$dirty && scheduleForm.title.$invalid }">
<label class="control-label" for="title">Title</label>
<div class="controls">
<input name="title" type="text" data-ng-model="title" id="title" class="form-control" placeholder="Title" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="content">Content</label>
<div class="controls">
<textarea name="content" data-ng-model="content" id="content" class="form-control" cols="30" rows="10" placeholder="Content"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label" for="start">Start</label>
<div class="controls">
<input name="finish" value="" type="date" data-ng-model="start" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="finish">Finish</label>
<div class="controls">
<input name="finish" value ="" type="date" data-ng-model="finish", class="form-control" required>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-default">
</div>
<div data-ng-show="error" class="text-danger">
<strong data-ng-bind="error"></strong>
</div>
</fieldset>
</form>
</div>
</section>
Here's the code for my controller:
'use strict';
angular.module('schedules').controller('SchedulesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Schedules',
function($scope, $stateParams, $location, Authentication, Schedules) {
$scope.authentication = Authentication;
$scope.create = function() {
var schedule = new Schedules({
title: this.title,
content: this.content,
start: this.start,
finish: this.finish
});
schedule.$save(function(response) {
$location.path('schedules/' + response._id);
console.log('hola!');
$scope.title = '';
$scope.content = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.remove = function(schedule) {
if (schedule) {
schedule.$remove();
for (var i in $scope.schedules) {
if ($scope.schedules[i] === schedule) {
$scope.schedules.splice(i, 1);
}
}
} else {
$scope.schedule.$remove(function() {
$location.path('schedules');
});
}
};
$scope.update = function() {
var schedule = $scope.schedule;
schedule.$update(function() {
$location.path('schedules/' + schedule._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.find = function() {
$scope.schedules = Schedules.query();
};
$scope.findOne = function() {
$scope.schedule = Schedules.get({
scheduleId: $stateParams.scheduleId
});
};
}
]);
Um... Well guys.... I don't know WHY this worked, and everything in me tells me this wasn't the problem, BUT:
Notice line
<input name="finish" value ="" type="date" data-ng-model="finish", class="form-control" required>
The "," was a mistake (I wrote a script that ported everything from articles into schedule, maintining code structure and just changing all mentions of [Aa]rticle{s} -> [Ss]chedule{s}, and this was left over in that (for some reason, don't know where it came in). Anyway, I deleted the comment and ran grunt build && grunt test && grunt and it worked. I'm now getting the correct render.