AngularJS: Get template attribute value in controller - javascript

I am a newbie of angularjs using version 1.6.4. I am using this module leon/angular-upload for upload functionality, minify version. On successful upload request, server return json object of uploaded file information on onSuccess(response) function as you can see in my user-registration.template.html file. Now i need to take this json object to my controller so that i can save this information in my database. Below is the few lines of my code.
user-registration.template.html:
<form role="form">
<div class="form-group float-label-control">
<label>Name</label>
<input type="text" placeholder="Name" class="form-control" ng-model="model.user.name">
</div>
<!-- leon/angular-upload -->
<div upload-button
url="/user_uploads"
on-success="onSuccess(response)"
on-error="onError(response)">Upload</div>
<div class="text-center">
<button type="button" class="btn btn-default" ng-click="model.save(model.user)">Save</button>
</div>
</form>
My component "user-registration.component.js":
(function(){
"use strict";
var module = angular.module(__appName);
function saveUser(user, $http){
var url = user.id > 0 ? __apiRoot + "/users/" + user.id : __apiRoot + "/users";
var dataObj = {
payload: JSON.stringify(user),
_method: "PUT"
}
return $http.post(url, dataObj);
}
function controller($http){
var model = this;
model.user = null;
model.save = function(user){
console.log(JSON.stringify(user));
saveUser(user, $http).then(function(response){
alert(response.data.msg);
});
}
}
module.component("userRegistration", {
templateUrl: "components/user-registration/user-registration.template.html",
bindings: {
value: "<"
},
controllerAs: "model",
controller: ["$http", controller]
});
}());

Try to put your server response data to rootScope model for Exempel :
$rootScope.serveResponse = response ;
and with this rootScope you can share your variable data between controller

Related

Angular not updating page after http request (scope issue?)

When my page loads, all the items in my mongo db are displayed. I have a form to input new entries, or delete entries. When creating or deleting, the http process works, but the new data is not updated in the DOM.
Most of the related questions I have researched suggest to make sure my ng-controller wraps the entire body, which it does. Other's suggest to use $apply, but I've also read that this is wrong. When I try it, I am alerted "in progress" anyway.
My only guess is that after the http request, a new scope is loaded and angular doesn't pick up on that. Or for some reason its just not reloading the data after my request. Here is my code, thanks for your help.
index.html
<body ng-controller="MainController">
<!-- list records and delete checkbox -->
<div id="record-list" class="row">
<div class="col-sm-4 col-sm-offset-4">
<!-- loop over records in $scope.records -->
<div class="checkbox" ng-repeat="record in records">
<label>
<input type="checkbox" ng-click="deleteRecord(record._id)">
{{ record.artist}} - {{ record.album }} - {{ record.bpm}}
</label>
</div>
</div>
</div>
<!-- record form data -->
<div id="record-form" class="row">
<div class="col-sm-8 col-sm-offset-2 text-center">
<form>
<div class="form-group">
<input type="artist" class="form-control input-lg text-center" placeholder="Artist" ng-model="formData.artist">
</div>
<div class="form-group">
<input type="album" class="form-control input-lg text-center" placeholder="Album" ng-model="formData.album">
</div>
<div class="form-group">
<input type="bpm" class="form-control input-lg text-center" placeholder="BPM" ng-model="formData.bpm">
</div>
<button type="submit" class="btn btn-primary btn-lg" ng-click="createRecord()">Add</button>
</form>
</div>
</div>
</div>
controller.js
angular.module('myApp', []).controller('MainController', ['$scope', '$http', function ($scope, $http) {
$scope.formData = {};
$scope.sortType = 'artist';
$scope.sortReverse = false;
//$scope.searchRecords = '';
$http.get('/api/records/')
.success(function(data) {
$scope.records = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
$scope.createRecord = function() {
$http.post('/api/records/', $scope.formData)
.success(function(data) {
//$scope.formData = {};
$scope.records = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
$scope.deleteRecord = function(id) {
$http.delete('/api/records/' + id)
.success(function(data) {
$scope.records = data;
console.log("delete record scope: " + data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}])
Your controller JS looks fine - I would say from looking at this that you need to export the updated values from your mongoDB collection when the POST/DELETE is successful.
If you use Mongoose (mongoDB plugin), you can update your API code to send back the updated data upon success with something like this:
// POST
// --------------------------------------------------------
// Provides method for saving new record to the db, then send back list of all records
app.post('/api/records', (req, res) => {
// Creates a new record based on the Mongoose Schema
const newRecord= new Record(req.body);
// New record is saved to the db
newRecord.save((err) => {
// Test for errors
if(err) res.send(err);
// Now grab ALL data on records
const all = Records.find({});
all.exec((err, records) => {
// Test for errors
if(err) res.send(err);
// If no errors are found, it responds with JSON for all records
res.json(records);
});
});
});

How to pass data one page to another page using angular js?

Here I am Trying to Login with user credientials
if user is valid , I want to pass UserName,LastloginTime,Role values to another page using angular js
<form role="form" ng-app="MyApp" ng-controller="MasterController">
<div class="form-group">
<label>
Username</label>
<input type="text" class="form-control" placeholder="Username" required ng-model="username" />
</div>
<div class="form-group">
<label>
Password</label>
<input type="password" class="form-control" placeholder="Password" required ng-model="password" />
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="remember">
Remember my Password
</label>
</div>
<input type="button" value="Submit" ng-click="GetData()" class="btn btn-danger" />
<%--<button type="button" class="btn btn-danger" ng-click="GetData()">Submit</button>--%>
<span ng-bind="Message"></span>
</form>
js file here
$scope.GetData = function () {
debugger;
var data = { UserName: $scope.username, Password: $scope.password };
$http.post("api/Test/CheckUsername", data)
.success(function (data, status, headers, config) {
if (data != "") {
$scope.Employees = data;
window.location.href = "EmployeeMaster";
//$scope.Reporting = data;
}
else {
alert("Invalid Credientials");
}
});
}
I want to display values in a master page
<table class="table">
<tr ng-repeat="Emp in Employees">
<th>User </th>
<td>:</td>
<td>{{Emp.username}}</td>
</tr>
<tr>
<th>Designation </th>
<td>:</td>
<td>{{Emp.RoleName}}</td>
</tr>
<tr>
<th>Last Login </th>
<td>:</td>
<td>{{Emp.LastLogin}}</td>
</tr>
</table>
How can i pass the values login page to Home page?
I suggest creating a service to store your global data:
myApp.factory('DataService', function() {
var user = {
name: '',
role: ''
// and so on
};
return {
user: user
};
});
Just inject this to all your controllers and set and retrieve the data you need:
myApp.controller('MyCtrl', function($scope, DataService) {
// make your DataService available in your scope
$scope.DataService = DataService;
});
This lets you bind models globally to the DataService.
Check out angular-storage A Storage done right for AngularJS. It is great for storing user info/tokens/ any object.
Key Features
Uses localStorage or sessionStorage by default but if it's not available, it uses ngCookies.
Lets you save JS Objects
If you save a Number, you get a Number, not a String
Uses a caching system so that if you already have a value, it won't get it from the store again.
https://github.com/auth0/angular-storage
There is lot of ways of to achieve this
1) Use $rootscope like you use $scope like
$rootscope.userName = ""
Inject the $rootscope dependency in the controller where you want to show it and create an object name Employee and fill it with $rootscope.
2) use constant like
module.constant("userData", data);
Inject the userData dependency in the controller where you want to show it and create an object name Employee and fill it with userData.
3) You can use service/factory and save the data in localstorage/sessionstorage
to transfer data between pages, you can use stateParams:
in the routes file:
$stateProvider
.state('employeeMasterState', {
url: '/employeeMasterUrl/:employeeData',
templateUrl: 'info/employeeMaster.tpl.html',
controller: 'employeeMasterCtrl',
controllerAs: 'employeeMasterCtrlAs'
});
js:
$scope.GetData = function () {
debugger;
var data = { UserName: $scope.username, Password: $scope.password };
$http.post("api/Test/CheckUsername", data)
.success(function (data, status, headers, config) {
if (data != "") {
this.state.go('employeeMasterState',{employeeData:data});
}
else {
alert("Invalid Credientials");
}
});
}
in the next page js:
constructor($scope, $statePArams){
$scope.empData = $stateParams.data;
}
You can create a service or a factory to share data between webpages. Here is the documentation

angular promise - on submit gets "Error: args is null $parseFunctionCall"

I am currently following this tuto on MEAN.js : https://thinkster.io/mean-stack-tutorial/ .
I am stuck into the end of "Wiring Everything Up", I am completlty new to angular so I am not pretending I understood everything I did. Here is the situation :
We are using the plugin ui-router.
First here is the html template :
<form name="addComment" ng-submit="addComment.$valid && addComment()"novalidate>
<div class="form-group">
<input class="form-control" type="text" placeholder="Comment" ng-model="body" required/>
</div>
<button type="submit" class="btn btn-primary">Comment</button>
</form>
The error "Error: args is null $parseFunctionCall" occurs only when I submit the form
Then, here is the configuration step for this page :
app.config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('posts', {
url : '/posts/{id}',
templateUrl: '/posts.html',
controller : 'PostsCtrl',
resolve : {
post: ['$stateParams', 'posts', function ($stateParams, posts) {
return posts.get($stateParams.id);
}]
}
});
$urlRouterProvider.otherwise('home');
}]);
There, is the controller :
app.controller('PostsCtrl', ['$scope', 'posts', 'post',
function ($scope, posts, post) {
$scope.post = post;
$scope.addComment = function () {
posts.addComment(post._id, {
body : $scope.body,
author: 'user'
}).success(function (comment) {
$scope.post.comments.push(comment);
});
$scope.body = '';
};
$scope.incrementUpVote = function (comment) {
posts.upvoteComment(post, comment);
};
}]);
And Finally, the factory where the posts are retrieved from a remote webservice
app.factory('posts', ['$http', function ($http) {
var o = {
posts: []
};
o.get = function (id) {
return $http.get('/posts/' + id).then(function (res) {
return res.data;
});
};
o.addComment = function (id, comment) {
return $http.post('/posts/' + id + '/comments', comment);
};
return o;
}]);
I've only given the parts that I think are relevant.
I suspect that the problem is comming from the promise and the scope which have been unlinked. I searched about promises but I think that ui-router is doing it differently.
I tried some $watch in the controller but without succeding.
Has anyone some idea about that ? Thank you in advance
The form name addComment (used for addComment.$valid) and the function addComment added to the scope are clashing with each other, rename one or the other.
See the Angular docs for the form directive:
If the name attribute is specified, the form controller is published
onto the current scope under this name.
As you are manually also adding a function named addComment, it is using the wrong one when evaluating the ng-submit.

Getting undefined in AngularJS

I'm working on building a little app that accepts input from a form (the input being a name) and then goes on to POST the name to a mock webservice using $httpBackend. After the POST I then do a GET also from a mock webservice using $httpBackend that then gets the name/variable that was set with the POST. After getting it from the service a simple greeting is constructed and displayed back at the client.
However, currently when the data gets displayed now back to the client it reads "Hello undefined!" When it should be reading "Hello [whatever name you inputed] !". I used Yeoman to do my app scaffolding so I hope everyone will be able to understand my file and directory structure.
My app.js:
'use strict';
angular
.module('sayHiApp', [
'ngCookies',
'ngMockE2E',
'ngResource',
'ngSanitize',
'ngRoute'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
})
.run(function($httpBackend) {
var name = 'Default Name';
$httpBackend.whenPOST('/name').respond(function(method, url, data) {
//name = angular.fromJson(data);
name = data;
return [200, name, {}];
});
$httpBackend.whenGET('/name').respond(name);
// Tell httpBackend to ignore GET requests to our templates
$httpBackend.whenGET(/\.html$/).passThrough();
});
My main.js:
'use strict';
angular.module('sayHiApp')
.controller('MainCtrl', function ($scope, $http) {
// Accepts form input
$scope.submit = function() {
// POSTS data to webservice
setName($scope.input);
// GET data from webservice
var name = getName();
// Construct greeting
$scope.greeting = 'Hello ' + name + ' !';
};
function setName (dataToPost) {
$http.post('/name', dataToPost).
success(function(data) {
$scope.error = false;
return data;
}).
error(function(data) {
$scope.error = true;
return data;
});
}
// GET name from webservice
function getName () {
$http.get('/name').
success(function(data) {
$scope.error = false;
return data;
}).
error(function(data) {
$scope.error = true;
return data;
});
}
});
My main.html:
<div class="row text-center">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<img src="../images/SayHi.png" class="logo" />
</div>
</div>
<div class="row text-center">
<div class="col-xs-10 col-xs-offset-1 col-md-4 col-md-offset-4">
<form role="form" name="greeting-form" ng-Submit="submit()">
<input type="text" class="form-control input-field" name="name-field" placeholder="Your Name" ng-model="input">
<button type="submit" class="btn btn-default button">Greet Me!</button>
</form>
</div>
</div>
<div class="row text-center">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<p class="greeting">{{greeting}}</p>
</div>
</div>
At the moment your getName() method returns nothing. Also you cant just call getName() and expect the result to be available immediately after the function call since $http.get() runs asynchronously.
You should try something like this:
function getName () {
//return the Promise
return $http.get('/name').success(function(data) {
$scope.error = false;
return data;
}).error(function(data) {
$scope.error = true;
return data;
});
}
$scope.submit = function() {
setName($scope.input);
//wait for the Promise to be resolved and then update the view
getName().then(function(name) {
$scope.greeting = 'Hello ' + name + ' !';
});
};
By the way you should put getName(), setName() into a service.
You can't return a regular variable from an async call because by the time this success block is excuted the function already finished it's iteration.
You need to return a promise object (as a guide line, and preffered do it from a service).
I won't fix your code but I'll share the necessary tool with you - Promises.
Following angular's doc for $q and $http you can build yourself a template for async calls handling.
The template should be something like that:
angular.module('mymodule').factory('MyAsyncService', function($q, http) {
var service = {
getNames: function() {
var params ={};
var deferObject = $q.defer();
params.nameId = 1;
$http.get('/names', params).success(function(data) {
deferObject.resolve(data)
}).error(function(error) {
deferObject.reject(error)
});
return $q.promise;
}
}
});
angular.module('mymodule').controller('MyGettingNameCtrl', ['$scope', 'MyAsyncService', function ($scope, MyAsyncService) {
$scope.getName = function() {
MyAsyncService.getName().then(function(data) {
//do something with name
}, function(error) {
//Error
})
}
}]);

AngularJS Uploading An Image With ng-upload

I am trying to upload a file in AngularJS using ng-upload but I am running into issues. My html looks like this:
<div class="create-article" ng-controller="PostCreateCtrl">
<form ng-upload method="post" enctype="multipart/form-data" action="/write" >
<fieldset>
<label>Category</label>
<select name="category_id" class="">
<option value="0">Select A Category</option>
<?php foreach($categories as $category): ?>
<option value="<?= $category -> category_id; ?>"><?= $category -> category_name; ?></option>
<?php endforeach; ?>
</select>
<label>Title</label>
<input type="text" class="title span5" name="post_title"
placeholder="A catchy title here..."
value="<?= $post -> post_title; ?>" />
<label>Attach Image</label>
<input type="file" name="post_image" />
<a href='javascript:void(0)' class="upload-submit: uploadPostImage(contents, completed)" >Crop Image</a>
<label>Body</label>
<div id="container">
<textarea id="mytextarea" wrap="off" name="post_content" class="span7" placeholder="Content..."><?= $post -> post_content; ?></textarea>
</div>
<div style='clear:both;'></div>
<label>Preview</label>
<div id='textarea-preview'></div>
</fieldset>
<div class="span7" style="margin: 0;">
<input type="submit" class="btn btn-success" value="Create Post" />
<input type="submit" class="btn btn-warning pull-right draft" value="Save as Draft" />
</div>
</form>
</div>
And my js controller looks like this:
ClabborApp.controller("PostCreateCtrl", ['$scope', 'PostModel',
function($scope, PostModel) {
$scope.uploadPostImage = function(contents, completed) {
console.log(completed);
alert(contents);
}
}]);
The problem I am facing is when the crop image is hit and it executes uploadPostImage, it uploads the entire form. Not desired behavior but I can make it work. The big problem is in the js the function uploadPostImage 'contents' parameters is always undefined, even when the 'completed' parameter comes back as true.
The goal is to only upload an image for cropping. What am I doing wrong in this process?
There's little-no documentation on angular for uploading files. A lot of solutions require custom directives other dependencies (jquery in primis... just to upload a file...). After many tries I've found this with just angularjs (tested on v.1.0.6)
html
<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>
Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.
controller
$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post(uploadUrl, fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success( ...all right!... ).error( ..damn!... );
};
The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.
You can try ng-file-upload angularjs plugin (instead of ng-upload).
It's fairly easy to setup and deal with angularjs specifics. It also supports progress, cancel, drag and drop and is cross browser.
html
<!-- Note: MUST BE PLACED BEFORE angular.js-->
<script src="ng-file-upload-shim.min.js"></script>
<script src="angular.min.js"></script>
<script src="ng-file-upload.min.js"></script>
<div ng-controller="MyCtrl">
<input type="file" ngf-select="onFileSelect($files)" multiple>
</div>
JS:
//inject angular file upload directives and service.
angular.module('myApp', ['ngFileUpload']);
var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
$scope.upload = $upload.upload({
url: 'server/upload/url', //upload.php script, node.js route, or servlet url
data: {myObj: $scope.myModelObj},
file: file,
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).then(function(response) {
var data = response.data;
// file is uploaded successfully
console.log(data);
});
}
};
}];
In my case above mentioned methods work fine with php but when i try to upload files with these methods in node.js then i have some problem.
So instead of using $http({..,..,...}) use the normal jquery ajax.
For select file use this
<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this)"/>
And in controller
$scope.uploadFile = function(element) {
var data = new FormData();
data.append('file', $(element)[0].files[0]);
jQuery.ajax({
url: 'brand/upload',
type:'post',
data: data,
contentType: false,
processData: false,
success: function(response) {
console.log(response);
},
error: function(jqXHR, textStatus, errorMessage) {
alert('Error uploading: ' + errorMessage);
}
});
};
var app = angular.module('plunkr', [])
app.controller('UploadController', function($scope, fileReader) {
$scope.imageSrc = "";
$scope.$on("fileProgress", function(e, progress) {
$scope.progress = progress.loaded / progress.total;
});
});
app.directive("ngFileSelect", function(fileReader, $timeout) {
return {
scope: {
ngModel: '='
},
link: function($scope, el) {
function getFile(file) {
fileReader.readAsDataUrl(file, $scope)
.then(function(result) {
$timeout(function() {
$scope.ngModel = result;
});
});
}
el.bind("change", function(e) {
var file = (e.srcElement || e.target).files[0];
getFile(file);
});
}
};
});
app.factory("fileReader", function($q, $log) {
var onLoad = function(reader, deferred, scope) {
return function() {
scope.$apply(function() {
deferred.resolve(reader.result);
});
};
};
var onError = function(reader, deferred, scope) {
return function() {
scope.$apply(function() {
deferred.reject(reader.result);
});
};
};
var onProgress = function(reader, scope) {
return function(event) {
scope.$broadcast("fileProgress", {
total: event.total,
loaded: event.loaded
});
};
};
var getReader = function(deferred, scope) {
var reader = new FileReader();
reader.onload = onLoad(reader, deferred, scope);
reader.onerror = onError(reader, deferred, scope);
reader.onprogress = onProgress(reader, scope);
return reader;
};
var readAsDataURL = function(file, scope) {
var deferred = $q.defer();
var reader = getReader(deferred, scope);
reader.readAsDataURL(file);
return deferred.promise;
};
return {
readAsDataUrl: readAsDataURL
};
});
*************** CSS ****************
img{width:200px; height:200px;}
************** HTML ****************
<div ng-app="app">
<div ng-controller="UploadController ">
<form>
<input type="file" ng-file-select="onFileSelect($files)" ng-model="imageSrc">
<input type="file" ng-file-select="onFileSelect($files)" ng-model="imageSrc2">
<!-- <input type="file" ng-file-select="onFileSelect($files)" multiple> -->
</form>
<img ng-src="{{imageSrc}}" />
<img ng-src="{{imageSrc2}}" />
</div>
</div>

Categories

Resources