update the data dynamically in AngularJS - javascript

I have two end points
http://localhost:3000/entry (POST)
Keys are :- fname, lname and age . We can submit a form by sending a POST request to this URL.
http://localhost:3000/entries (GET)
It will return the existing data from the database in a JSON.
[
{
"_id": "5b48a137c3b2a3454b853a3c",
"fname": "John",
"lname": "Jose",
"age": "28",
"__v": 0
},
{
"_id": "5b506cc7d9105012f59c87e6",
"fname": "Alex",
"lname": "Cruz",
"age": "27",
"__v": 0
}
]
I can successfully submit a form. In my HTML, I also have a table. I want to update the data in the table whenever I submit an entry without reloading the whole page.
Actually, data in this API http://localhost:3000/entries is dynamic, sometimes, I insert into database directly. So, whenever there is a change, it should reflect in the table without reloading the whole page.
I am using AngularJS 1.
index.html :-
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
<div ng-app="myApp">
<div class="container">
<div class="row">
<div class="col-sm-12">
<h3>
Dashboard
</h3>
</div>
</div>
<form name="saveTemplateData" action="#" ng-controller="FormCtrl" ng-submit="submitForm()" >
<div class="col-sm-12">
<div class="form-group">
<label>FirstName</label>
<input type="text" class="form-control" value="" ng-model="form.fname" />
</div>
<div class="form-group">
<label>LastName</label>
<input type="text" class="form-control" value="" ng-model="form.lname" />
</div>
<div class="form-group">
<label>Age</label>
<input type="text" class="form-control" value="" ng-model="form.age" />
</div>
</div>
<div class="col-sm-12">
<input type="submit" class="btn btn-success" ngClick="Submit">
</div>
</form>
<!-- Table Start -->
<div class="row">
<table style="width:100%">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<tr>
<!-- item.fname -->
<td>{{item.fname}}</td>
<!-- item.lname -->
<td>{{item.lname}}</td>
<!-- item.age -->
<td>{{item.age}}</td>
</tr>
</table>
</div>
<!-- Table END -->
</div>
</div>
script.js :-
var app = angular.module('myApp', []);
app.controller('FormCtrl', function ($scope, $http) {
$scope.submitForm = function()
{
$http({
url: "http://localhost:3000/entry",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param($scope.form)
}).then(function (response) {
$scope.status = status;
}), function (error) {
$scope.status = status;
};
}
});

If I understand your question and problem(s), you'll need to do a number of things to resolve your issues.
Firstly, you'll want to make some extensions to your controller. The main one being to fetch the data from your API:
app.controller('FormCtrl', function ($scope, $http, $interval) {
/*
Add this method to get data from server
*/
$scope.fetchData = function() {
// It is best practice to handle error responses as well (not
// shown here)
$http.get('http://localhost:3000/entries').then(function(response) {
// Set the data items in your scope. Doing this should now
// cause them to be listed in your view
$scope.items = response.data;
});
}
$scope.submitForm = function($event) {
// Adding this prevents the browser from reloading on form submit
$event.preventDefault()
$http({
url: "http://localhost:3000/entry",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param($scope.form)
}).then(function (response) {
$scope.status = status;
}), function (error) {
$scope.status = status;
});
}
// Fetch data once controller is set up, on a regular 2 second
// interval
$interval(function() {
$scope.fetchData()
}, 2000)
});
You'll also need to update your HTML/view:
<!-- Add $event as an argument to you ng-submit callback -->
ng-submit="submitForm($event)"
And:
<!-- Doing this causes the data in the items array to be iterated
and displayed in a list-wise fashion in the table -->
<tr ng-repeat="item in items">
<!-- item.fname -->
<td>{{item.fname}}</td>
<!-- item.lname -->
<td>{{item.lname}}</td>
<!-- item.age -->
<td>{{item.age}}
</td>
</tr>
Finally, the most important thing is to wrap the table and form with your FormCtrl controller. You can do this by moving ng-controller="FormCtrl" from your <form> element, to your <div class="container"> element in your view.

Related

$filter ui-grid using search fields

At the moment I have a ui-grid with a full name and registration columns. I also have search fields for both. If user searches for registration, the table is updated 'on the fly'. My issue is that if the user enters both to narrow down the search e.g. registration and name at the same time. The table only reacts on a single filter input.
This is part of my code responsible for watching the field vm.model.employeeName and vm.model.registrationName which are the search fields. vm.resultData is an array of rows to be inserted into vm.gridOptions.data (the ui-grid).
vm.watchFilter = function() {
if (vm.model.employeeName || vm.model.registrationNumber) {
if (vm.model.employeeName) {
vm.updatedResultData = $filter('filter')(vm.resultData, {employeeFullName: vm.model.employeeName});
}
if(vm.model.registrationNumber) {
vm.updatedResultData = $filter('filter')(vm.resultData, {currentVehicleRegistration: vm.model.registrationNumber});
}
vm.gridOptions.data = vm.updatedResultData;
} else {
vm.gridOptions.data = vm.resultData;
}
vm.numberOfRecords = vm.gridOptions.data.length;
};
$scope.$watch('vm.model.employeeName', vm.watchFilter);
$scope.$watch('vm.model.registrationNumber', vm.watchFilter);
How do I combine the 2 to get narrowed down search? I've spent hours on this...
I don't want to end up with if statements for every possible search as I might add an extra search field in the future. Also if a user decides to enter reg first and then name.....
I hope this will help you. Thank you.
var app = angular.module('app', ['ngMessages']);
app.controller('pageCtrl', ['$scope', '$http', function($scope, $http) {
$scope.names = [{"Name":"Mark","Number":"10000"},
{"Name":"Steve","Number":"20000"},
{"Name":"Bill","Number":"30000"},
{"Name":"John","Number":"40000"},
{"Name":"Luis","Number":"50000"}];
$scope.search = function(){
$scope.criteria = angular.copy($scope.criteria1);
}
}]);
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-messages.min.js"></script>
<div ng-app="app" class="container" >
<h1>Filter Name & Registeration Number</h1>
<hr />
<form ng-controller="pageCtrl" ng-init='getData()'>
<div class='form-group'>
<div class='row'>
<div class="right-inner-addon col-md-4 ">
<input type="search" ng-model='model.Name' class="form-control" placeholder="Name">
</div>
<div class="right-inner-addon col-md-4 ">
<input type="search" ng-model='model.Number' class="form-control" placeholder="Registeration Number">
</div>
</div>
</div>
<table class="table table-bordered" >
<tr>
<th>Name</th>
<th>Registeration Number</th>
<tr>
<tr ng-repeat="item in filtered = (names | filter : model)">
<td>{{item.Name}}</td>
<td>{{item.Number}}</td>
<tr>
</table>
</form>
</div>

Process maker - Login using rest api not working

Using the below script i am able to retrieve the cases related to a particular user using process makers rest api, but unable to go the home page and use the system as is (Somthing like a single sign on) after doing this, what am i missing here? I am redirecting to the page i want and its taking me to the login screen again. i am using app.js to call the rest api and index.php to display and enter login credentials. I am following this tutorial http://www.processmaker.com/tutorial-rest-api-angularjs, Please help
My app.js is as below:
(function () {
var app;
app = angular.module('caseLister',[]);
app.controller('listController', ['$http', '$scope', function($http, $scope){
this.server_url = 'http://localhost';
this.workspace = 'workflow';
this.credentials = {
grant_type : 'password',
scope : '*',
client_id : 'GFFBDLKMOFFGRLQXELEOIBUVWQXUYANB',
client_secret: '3429870605882e9af901eb4035842469',
username : '',
password : ''
};
var access_token = '';
var list = this;
this.login = function () {
var parameters = {
method: 'POST',
url: list.server_url+list.workspace+'/oauth2/token',
data: this.credentials
};
$http(parameters).success(function(data){
if (data.error) {
alert(data.error_description);
}else {
parameters = {
method: 'GET',
url: list.server_url+'api/1.0/'+list.workspace+'/cases',
headers: {'Authorization': 'Bearer '+data.access_token}
};
$http(parameters).success(function(data){
location.href="http://localhost/sysworkflow/en/neoclassic/cases/main";
list.cases = data;
});
}
});
};
}]);
})();
My index.php is as below:
<!DOCTYPE html>
<html ng-app="caseLister">
<head>
<link rel="shortcut icon" type="image/x-icon" href="http://www.processmaker.com/favicon.ico" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="listController as list">
<div class="panel panel-primary">
<div class="panel-heading">
<h1>ProcessMaker Case Lister</h1>
<h6>Build your own user interface using the new ProcessMaker REST API</h6>
</div>
<div class="panel-body">
<div class="well well-sm col-xs-4 pull-right">
<h4>PM Server details</h4>
<strong>URL:</strong> {{list.server_url}}<br>
<strong>Workspace:</strong> {{list.workspace}}<br>
<strong>Client ID:</strong> {{list.credentials.client_id}}<br>
<strong>Client Secret:</strong> {{list.credentials.client_secret}}
</div>
<form>
<div class="input-group col-xs-6">
<div class="input-group-addon">Username:</div>
<input type="text" class="form-control" ng-model="list.credentials.username">
</div><br>
<div class="input-group col-xs-6">
<div class="input-group-addon">Password:</div>
<input type="password" class="form-control" ng-model="list.credentials.password">
</div><br>
<input class="btn btn-info" type="button" value="Get Case List" ng-click="list.login()"><br>
</form>
<div ng-show="list.cases.length > 0">
<h3>CASE LIST ({{list.cases.length}})</h3>
<table class="table table-hover table-bordered">
<thead><tr class="bg-primary">
<th>#</th>
<th>Case Number</th>
<th>Process</th>
<th>Task</th>
<th>Sent By</th>
<th>Due Date</th>
<th>Status</th></tr></thead>
<tr ng-repeat="case in list.cases">
<td>{{$index + 1}}</td>
<td>{{case.app_number}}</td>
<td>{{case.app_pro_title}}</td>
<td>{{case.app_tas_title}}</td>
<td>{{case.app_del_previous_user}}</td>
<td>{{case.del_task_due_date}}</td>
<td>{{case.app_status}}</td></tr>
</table>
</div>
</div>
</div>
</div>
</body>
</html>

AngularJS move part of Controller to Service

Consider the following code.
HTML:
<!doctype html>
<html ng-app="todoApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link href="/css/overlay-control.css" rel="stylesheet">
<link href="/css/list-control.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!--<script src="/js/Services/UserService.js"></script>-->
<script src="/js/Controllers/MainController.js"></script>
<!--<script src="/js/Controllers/UserController.js"></script>-->
<script src="/js/bootstrap.min.js"></script>
</head>
<body ng-controller="MainController as myControl">
<div id="overlaycover" ng-click="myControl.showUpd(0)"></div>
<div id="overlaybox">
<div class="col-md-12">
<h4>Update:</h4>
<form ng-submit="myControl.updTodo()">
<div class="form-group">
<label for="updContent">Note:</label>
<textarea rows="5" cols="30" class="form-control" id="updContent" name="updContent" ng-model="noteupd.content"></textarea>
</div>
<div class="form-group">
<label for="updDeadline">Deadline (format YYYY-MM-DD HH:MM:SS):</label>
<input type="text" class="form-control" id="updDeadline" name="updDeadline" ng-model="noteupd.deadline" />
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="updCompleted" name="updCompleted" ng-model="noteupd.completed" /> - Completed
</label>
</div>
<div class="form-group">
<input type="hidden" id="updID" ng-model="noteupd.id" /><br/>
<button type="submit" class="btn btn-info">Update</button>
</div>
</form>
Click utside the square to close.
</div>
</div>
<div class="container">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" id="listDiv">
<h1>Todo-list:</h1>
<p>
<img src="/images/legend-normal.png"> - Unfinished 
<img src="/images/legend-completed.png"> - Finished 
<img src="/images/legend-late.png"> - Late
</p>
<table class="table" id="list-table">
<tr>
<th>Note:</th>
<th>Author:</th>
<th>Project:</th>
<th>Created:</th>
<th>Deadline:</th>
<th colspan="2">Modify:</th>
</tr>
<tr ng-repeat="todo in myControl.todos" ng-class="rowClass(todo.completed, todo.deadline)">
<td> {{ todo.content }} </td>
<td> {{ todo.user }} </td>
<td> {{ todo.project }} </td>
<td> {{ todo.created }} </td>
<td> {{ todo.deadline }} </td>
<td><button type="button" class="btn btn-info" ng-click="myControl.showUpd(todo.id)">Update</button></td>
<td><button type="button" class="btn btn-danger" ng-click="myControl.delTodo(todo.id)">Delete</button></td>
</tr>
</table>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" id="formDiv">
<h3>Add new note:</h3>
<form ng-submit="myControl.addTodo()">
<div class="form-group">
<label for="newUser">User:</label>
<select ng-model="noteadd.user" class="form-control" id="newUser" name="newUser">
<option ng-repeat="user in myControl.users" value="{{ user.id }}">{{ user.name }}</option>
</select><br/>
</div>
<div class="form-group">
<label for="newProject">Project:</label>
<select ng-model="noteadd.project" class="form-control" id="newProject" name="newProject">
<option ng-repeat="project in myControl.projects" value="{{ project.id }}">{{ project.name }}</option>
</select><br/>
</div>
<div class="form-group">
<label for="newContent">Note:</label>
<textarea rows="5" cols="30" ng-model="noteadd.content" class="form-control" id="newContent" name="newContent"></textarea><br/>
</div>
<div class="form-group">
<label for="newDeadline">Deadline (format YYYY-MM-DD HH:MM:SS):</label>
<input type="text" ng-model="noteadd.deadline" class="form-control" id="newDeadline" name="newDeadline" /><br/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-info">Add</button>
</div>
</form>
</div>
</div>
</body>
</html>
AngularJS Controller:
angular.module('todoApp', []).controller('MainController', function($scope, $http) {
var thisApp = this;
$scope.noteadd = {};
var noteadd = $scope.noteadd;
$scope.noteupd = {};
var noteupd = $scope.noteupd;
// Get all notes:
$http({method : 'GET', url : 'http://localhost:8000/notes'})
.then (function(response) {
thisApp.todos = response.data;
}, function() {
alert("Error getting todo notes");
});
// Get all users:
$http({method : 'GET',url : 'http://localhost:8000/users'})
.then(function(response) {
thisApp.users = response.data;
}, function() {
alert("Error getting users");
});
// Get all projects
$http({method : 'GET', url : 'http://localhost:8000/projects'})
.then(function(response) {
thisApp.projects = response.data;
}, function() {
alert("Error getting projects");
});
// Add note to database
thisApp.addTodo = function(noteadd)
{
$http({
method : 'PUT',
url : 'http://localhost:8000/notes',
data : $.param($scope.noteadd),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't add note. Please try again!");
});
};
// Hide note by setting removed to 1
thisApp.delTodo = function(noteID)
{
var r = confirm("Are you sure?");
if (r == true) {
var noteObj = JSON.parse('{"id":' + noteID + '}'); // JSON for req
$http({
method : 'DELETE',
url : 'http://localhost:8000/notes',
data : $.param(noteObj),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't delete note. Please try again!");
});
}
};
// Show overlay with form for updating a note
thisApp.showUpd = function(noteID)
{
var overlaycover = document.getElementById("overlaycover");
var overlaybox = document.getElementById("overlaybox");
overlaycover.style.opacity = .65;
if(overlaycover.style.display == "block" || noteID == 0){ // For toggling overlay
overlaycover.style.display = "none"; // Hide div overlaycover
overlaybox.style.display = "none"; // Hide div overlaybox
} else {
$http({method : 'GET', url : 'http://localhost:8000/notes/' + noteID})
.then (function(response) {
noteupd.content = response.data.content; // Update fields in form
noteupd.deadline = response.data.deadline;
noteupd.id = response.data.id;
if (response.data.completed == 1) {
noteupd.completed = true;
} else {
noteupd.completed = false;
}
overlaycover.style.display = "block"; // Show div overlaycover
overlaybox.style.display = "block"; // Show div overlaybox
}, function() {
alert("Error getting todo note");
});
}
}
// Update a note
thisApp.updTodo = function(noteupd)
{
$http({
method : 'POST',
url : 'http://localhost:8000/notes',
data : $.param($scope.noteupd),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't add note. Please try again!");
});
}
// Check if deadline passed for each note in list
$scope.rowClass = function(completed, deadline)
{
var nowTime = Math.floor(Date.now()/1000);
var deadTime = new Date(deadline);
var deadUTC = Math.floor(deadTime/1000);
if (completed == 1) {
return "success"; // Note is completed
} else if (deadUTC < nowTime) {
return "danger"; // Note is not completed, deadline passed
} else {
return "active"; // Note is not completed, still time left
}
}
});
What I would like to do is to move all $http-calls to a service instead of having them in the controller like I have it now. I have searched the internet but I don't really understand the solutions i've found there.
Second, in several functions, as you can see, I use location.reload();. I would like to use ng-bind instead, but as the sam, I don't understand how this works.
Can someone please explain how I should do these two things?
Ok , let's for example create a Users factory and put all Users api related stuff inside:
'use strict';
angular
.module('todoApp')
.factory('Users', factory);
function factory($http) {
var service = {
get: get,
//edit: edit ...
};
return service;
function get() {
return $http({method : 'GET',url : 'http://localhost:8000/users'})
.then(function(response) {
return response.data;
});
}
//function edit(user) {
// return $http({method : 'PUT...
//}
}
What you have to do next is inject that factory wherever you want to call it.
So in your controller you essentially have to do this:
angular.module('todoApp', [])
.controller('MainController', function($scope, Users) {
//.....
function getUsers() {
Users.get().then(function(data){
thisApp.users = response.data;
}, function() {
alert("Error getting users");
});
}
getUsers();
//...
Repeat the same by creating the appropriate services for notes and projects.
To not bloat the main app.js move this services to seperate files, users.service.js etc..
I would also advise you to move the controllers to seperate files too.
Just be careful:
this is a module creation
angular.module('todoApp', [])
You create a module once.
to attach a service/factory/controller/anything, when you are in that separate file, to that module you use this:
angular.module('todoApp').anything
Second, I assume you use location.reload to update the view with the new data.
Let's say you edit/delete a User. Instead of reloading the page, call getUsers() in the then() of put/delete/create User.
Hope it makes sense to you!
PS: This styleguide by John Papas have been very helpful to me, I suggest you give it a read !
I've already used service factory solution for such kind of problem.
angular.module('data-service').factory('dataService', ['$http',function ($http) {
var url = 'http://localhost:8000/';
return {
getData: function(type) {
return $http({method : 'GET', url : url + type});
},
allData: function() {
return $q.all({
notes: this.getData('notes'),
users: this.getData('users'),
projects: this.getData('projects')
});
}
}
}]);
usage:
dataService.getData('notes').then(function (data) { ... });
also you can use angular promise $q.
dataService.allData().then(function(data) { /* data.notes, data.users, data.projects */ }

How to load data in ngDialog

I have a requirement where I need to open a dialog from a jsp page and while opening the dialog, I need to load it with some prepopulated data from the server (using an AJAX call). If I make the AJAX call before opening the dialog, I get the data but the dialog loads like a new page. If I try to get the data in the new controller, the dialog still does not reflect the data. What should I use to make sure the dialog reflects the data that I am getting from the server
<div class="container-fluid" ng-controller="EditUserController">
<div class="text-center container-fluid">
<label class="sub-header">Edit User: {{userEmail}}</label>
</div>
<form action="editUser" method="post" name="editForm">
<div>
<div class="pull-right">
<label>Delete User</label><br> <a href="#"
class="btn btn-block btn-sm btn-danger" ng-click="deleteUser(userEmail)">{{userEmail}}</a>
</div>
<div>
<label>Change Role</label>
</div>
<div>
<label>
<input type="checkbox" ng-model="superVisor" name="superVisorFlag"
ng-true-value="1" ng-false-value="0" value="${existingUser.superVisorFlag}">
Make a Supervisor</label>
</div>
<div>
<input type="text" class="form-control" ng-model="email"
name="emailAddress" ng-disabled = "true"
ng-options="email for email in userEmail"
value="${existingUser.emailAddress}"
placeholder="Enter New User Email Address" bs-typeahead>
</div>
<div>
<input type="text" class="form-control" ng-model="firstName"
name="firstName" value="${existingUser.firstName}"
placeholder="Enter First Name" bs-typeahead>
</div>
<div>
<input type="text" class="form-control" ng-model="lastName"
name="lastName" value="${existingUser.lastName}"
placeholder="Enter Last Name" bs-typeahead>
</div>
<div>
Save Changes
</div>
</div>
</form>
</div>
<script type="text/javascript"
src="<c:url value="/resources/scripts/admin.js"/>"></script>
The above is a jsp for the dialog. Below is my js file -
var app = angular.module('scc-admin', [ 'ngDialog', 'mgcrea.ngStrap' ]);
app.factory("UserList", function() {
var UserList = {};
UserList.data = [ {
userId : 111,
userFirstName : "xxx",
userLastName : "yyy",
userEmail : "xxx.yyy#zzz.com",
userRole : "Admin"
}, {
userId : 222,
userFirstName : "second",
userLastName : "last",
userEmail : "second.last#zzz.com",
userRole : "Manager"
}];
return UserList;
});
app.controller('UserSettingsController', function($scope, ngDialog, UserList,$http) {
// variable for the bashboard list
$scope.userList = UserList;
$scope.editUser = function(userEmail) {
$scope.userEmail = userEmail;
ngDialog.open({
template : 'editUser' ,
className : 'ngdialog-theme-default',
controller : 'EditUserController',
closeByEscape : true,
scope : $scope
});
};
$scope.addUser = function() {
ngDialog.open({
template : 'addUser',
className : 'ngdialog-theme-default',
controller : 'AddUserController',
closeByEscape : true,
scope : $scope
});
};
});
app.controller('EditUserController', function($scope, ngDialog, $http) {
ngDialog.template = $scope.output;
ngDialog.$modelValue = $scope.output;
var responsePromise = $http.get("initUser?email=" + $scope.userEmail);
responsePromise.success(function(data, status, headers, config) {
$scope.output = data;
console.log(data);
});
console.log($scope);
$scope.deleteUser = function(){
$scope.cfdump = "";
var str = {emailAddress : $scope.userForm.emailAddress.$modelValue};
str = JSON.stringify(str);
var request = $http({
method: 'post',
url: "deleteUser?formData=" + str,
data: ({formData:str})
});
request.success(function(html){
alert("success");
});
request.error(function(errmsg){
alert("Unable to delete user");
});
}
});
I am opening a dialog in usersettings controller and trying to load it with default data. I tried setting the new dialog's template to the output of the AJAX call, it did not work. What am I missing here?
After consulting the documentation, I learned following solution. It should work for you like it did for me.
To pass data (JSON Object) for ng-model inside the ngDialog, you can declare your ngDialog as following.
ngDialog.open({
template: 'my-template.html',
className: 'ngdialog-theme-plain',
data: $scope.myJSONObject
});
Now, with the above part done, you need to bind the data in your popup ngDialog, so go and put ngDialogData.myJSONObjectFieldName in your ng-model.
Consider following example for further elaboration. We assume that we have myJSONObject as following.
myJSONObject={
first_name: 'John',
last_name: 'Doe'
};
To use first_name inside your ngDialog's ng-model, simply put ng-model="ngDialogData.first_name".
To check whether the controller(VM) data is received in Modal Dialog use this
<pre>{{vm|json}}</pre>
Module and Controller:
var app = angular.module("DemoApp",['ngDialog']);
app.controller("DemoController",["$rootScope","ngDialog","productService",function($rootScope,ngDialog,productService){
var vm=this;
$rootScope.ngDialog = ngDialog; // to close Dialog using "ngDialog.close();" in ProductDialog.html
/* vm.products=[{brand:"Apple", price:60000, os:"iOS"},
{brand:"Samsung", price:35000, os:"Android"},
{brand:"Microsoft Lumia", price:30000, os:"Windows 10"}
];
*/
vm.getProductDetails=function() {
productService.getData().then(function (response) {
if (response.data) {
vm.products=response.data;
vm.ProdDialog();
}
});
};
vm.productPopup = function(x){
ngDialog.open({
template: 'ProductDialog.html',
className:'ProductDetailsDialog'
scope:$scope,
data:x,
closeByDocument:true
});
}
vm.getProductDetails();
}]);
Service:
app.factory("productService",["$http",function($http){
return {
getData: function() {
return $http.get("http://xxxxxxx/xxx/xxxxx");
}
};
}]);
DemoController.html
/* <table>
<tr>
<th>Brand</th>
<th>Price</th>
<th>OPerating System</th>
<th>Open ngDialog</th>
</tr>
<tr ng-repeat="x in vm.products">
<td ng-bind="x.brand"></td>
<td ng-bind="x.price| currency:"₹":2"></td>
<td ng-bind="x.os"></td>
<td><button ng-click="vm.productPopup(x)"></button></td>
</tr>
</table>
*/
ProductDialog.html:
<div class="ProductDetailsDialog">
<div class="ngdialog-content" role="document">
<div class="modal-header">
<button type="button" class="close" ng-click="ngDialog.close();">×</button>
<h4 class="modal-title">Product Detials</h4>
</div>
// <pre>{{vm|json}}</pre> //
<div class="modal-body">
<h4>Brand:<span ng-bind="ngDialogData.brand"></span></h4>
<h4>Price:<span ng-bind="ngDialogData.price | currency:"₹":2"></span></h4>
<p>Operating System:<span ng-bind="ngDialogData.os"></span></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default">OK</button>
</div>
</div>
</div>

Uncaught ReferenceError: $scope is not defined - AngularJS

I'm new to using AngularJS. However, why isn't this working?
Upon loading the webpage, I get in the console Uncaught ReferenceError: $scope is not defined on Line 81 which is $scope.processForm = function() { Help?
// define angular module/app
var formApp = angular.module('formApp', []);
// create angular controller and pass in $scope and $http
function formController($scope, $http) {
// create a blank object to hold our form information
// $scope will allow this to pass between controller and view
$scope.formData = {};
// process the form
$scope.processForm = function() {};
}
// process the form
$scope.processForm = function() {
$http({
method: 'POST',
url: 'process.php',
data: $.param($scope.formData), // pass in data as strings
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorName = data.errors.name;
$scope.errorSuperhero = data.errors.superheroAlias;
} else {
// if successful, bind success message to message
$scope.message = data.message;
}
});
};
<!-- LOAD ANGULAR -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<!-- LOAD BOOTSTRAP CSS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<!-- LOAD JQUERY -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<body ng-app="formApp" ng-controller="formController">
<div class="container">
<div class="col-sm-6 col-sm-offset-3">
<!-- PAGE TITLE -->
<div class="page-header">
<h1><span class="glyphicon glyphicon-tower"></span> Submitting Forms with Angular</h1>
</div>
<!-- SHOW ERROR/SUCCESS MESSAGES -->
<div id="messages" ng-show="message">{{ message }}</div>
<!-- FORM -->
<form ng-submit="processForm()">
<!-- NAME -->
<div id="name-group" class="form-group" ng-class="{ 'has-error' : errorName }">
<label>Name</label>
<input type="text" name="name" class="form-control" placeholder="Bruce Wayne" ng-model="formData.name">
<span class="help-block" ng-show="errorName">{{ errorName }}</span>
</div>
<!-- SUPERHERO NAME -->
<div id="superhero-group" class="form-group" ng-class="{ 'has-error' : errorSuperhero }">
<label>Superhero Alias</label>
<input type="text" name="superheroAlias" class="form-control" placeholder="Caped Crusader" ng-model="formData.superheroAlias">
<span class="help-block" ng-show="errorSuperhero">{{ errorSuperhero }}</span>
</div>
<!-- SUBMIT BUTTON -->
<button type="submit" class="btn btn-success btn-lg btn-block" ng-model="formData.XAlias">
<span class="glyphicon glyphicon-flash"></span> Submit!
</button>
</form>
</div>
</div>
<!-- SHOW DATA FROM INPUTS AS THEY ARE BEING TYPED -->
<pre>{{formData}}</pre>
Replace the empty $scope.processForm inside your controller (function formController($scope, $http)) with the one that's currently outside.
Inside the controller it'll have access to the $scope which you injected in.

Categories

Resources