Login for restfull api in angularjs and flask? - angularjs

I wand to create the login for rest-full api. I want to create similar application when page open first time then It pop-up with the login page. How I want to make Please see DEMO. This is developed in knockout+flask rest-api. I want to make same but I want to use Angularjs instead of Knockout.
My Code DEMO, In this I remove all the other code. Just want when page load It loads with login, and when I insert correct login credential it Login to rest-api.
rest-server.py
import six
from flask import Flask, jsonify, abort, request, make_response, url_for, render_template
from flask.ext.httpauth import HTTPBasicAuth
app = Flask(__name__, static_url_path="")
auth = HTTPBasicAuth()
#auth.get_password
def get_password(username):
if username == 'admin':
return '1234'
return None
#auth.error_handler
def unauthorized():
return make_response(jsonify({'error': 'Unauthorized access'}), 403)
#app.errorhandler(400)
def bad_request(error):
return make_response(jsonify({'error': 'Bad request'}), 400)
#app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
tasks = [
{
'id': 1,
'title': u'Buy groceries',
'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
'done': False
},
{
'id': 2,
'title': u'Learn Python',
'description': u'Need to find a good Python tutorial on the web',
'done': False
}
]
def make_public_task(task):
new_task = {}
for field in task:
if field == 'id':
new_task['uri'] = url_for('get_task', task_id=task['id'],
_external=True)
else:
new_task[field] = task[field]
return new_task
#app.route('/')
#auth.login_required
def index():
return render_template('index.html')
#app.route('/todo/api/v1.0/tasks', methods=['GET'])
#auth.login_required
def get_tasks():
return jsonify({'tasks': [make_public_task(task) for task in tasks]})
#app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET'])
#auth.login_required
def get_task(task_id):
task = [task for task in tasks if task['id'] == task_id]
if len(task) == 0:
abort(404)
return jsonify({'task': make_public_task(task[0])})
#app.route('/todo/api/v1.0/tasks', methods=['POST'])
#auth.login_required
def create_task():
if not request.json or 'title' not in request.json:
abort(400)
task = {
'id': tasks[-1]['id'] + 1,
'title': request.json['title'],
'description': request.json.get('description', ""),
'done': False
}
tasks.append(task)
return jsonify({'task': make_public_task(task)}), 201
#app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['PUT'])
#auth.login_required
def update_task(task_id):
task = [task for task in tasks if task['id'] == task_id]
if len(task) == 0:
abort(404)
if not request.json:
abort(400)
if 'title' in request.json and \
not isinstance(request.json['title'], six.string_types):
abort(400)
if 'description' in request.json and \
not isinstance(request.json['description'], six.string_types):
abort(400)
if 'done' in request.json and type(request.json['done']) is not bool:
abort(400)
task[0]['title'] = request.json.get('title', task[0]['title'])
task[0]['description'] = request.json.get('description',
task[0]['description'])
task[0]['done'] = request.json.get('done', task[0]['done'])
return jsonify({'task': make_public_task(task[0])})
#app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['DELETE'])
#auth.login_required
def delete_task(task_id):
task = [task for task in tasks if task['id'] == task_id]
if len(task) == 0:
abort(404)
tasks.remove(task[0])
return jsonify({'result': True})
if __name__ == '__main__':
app.run(debug=True)
My angular code angularjs.html
<!DOCTYPE html>
<html>
<head>
<title>ToDo API Client Demo By Angularjs</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" />
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="tasksCtrl">
<div class="navbar">
<div class="navbar-inner">
<a class="brand" href="#">ToDo API Client Demo</a>
</div>
</div>
<div>
<a class="btn" data-toggle="modal" data-target="#login">Login</a>
</div>
<div>
<table class="table table-striped">
<tbody>
<tr>
<td style="width: 1px;"></td>
<td>
<b>Task</b>
</td>
<td>
<b>Options</b>
</td>
</tr>
<tr ng-repeat="task in tasks">
<td>
<span ng-show="done" class="label label-success">Done</span>
<span ng-hide="done" class="label label-important">In Progress</span>
</td>
<td>{{task.title}}</td>
<td>{{task.description}}</td>
<td>
<a class="btn" data-toggle="modal" data-target="#modal" ng-click="editTask(task)">Edit</a>
</td>
<td>
<a class="btn" data-toggle="modal" data-ng-click="removeRow(task)">Delete</a>
</td>
<td ng-show="done">
<span>
<button ng-click="done = !done" class="btn">Mark In Progress</button>
</span>
</td>
<td ng-hide="done">
<span>
<button ng-click="done = !done" class="btn">Mark Done</button>
</span>
</td>
</tr>
</tbody>
</table>
<a class="btn" data-toggle="modal" data-target="#add" ng-click="editTask(task)">Add Task</a>
</div>
<div id="modal" role="dialog" class="modal hide fade">
<div>
<div class="modal-header">
Task Dialog
</div>
<div class="modal-body">
<label for="txtName"></label>
<input type="text" ng-model="selectedTask.title" />
<input type="text" ng-model="selectedTask.description" />
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="saveTask()" data-dismiss="modal">OK</button>
</div>
</div>
</div>
<div id="add" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="addDialogLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="addDialogLabel">Add Task</h3>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="inputTask">Task</label>
<div class="controls">
<input type="text" id="inputTask" ng-model="task1" placeholder="Task title" style="width: 150px;" />
<br />
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputDescription">Description</label>
<div class="controls">
<input type="text" id="inputDescription" ng-model="description1" placeholder="Description" style="width: 300px;" />
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="addNewTask()" data-dismiss="modal">Add Task</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
</div>
</div>
<div id="login" class="modal hide fade" tabindex="=1" role="dialog" aria-labelledby="loginLabel" aria-hidden="true">
<div class="modal-header">
<h3 id="loginLabel">Sign In</h3>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="inputUsername">Username</label>
<div class="controls">
<input data-bind="value: username" type="text" id="inputUsername" placeholder="Username">
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<input data-bind="value: password" type="password" id="inputPassword" placeholder="Password">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button data-bind="click: login" class="btn btn-primary" data-dismiss="modal" aria-hidden="true">Sign In</button>
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('tasksCtrl', function($scope, $http) {
//$http.get("data.json")
$http.get("/todo/api/v1.0/tasks")
.success(function(response) {
console.log(response.tasks)
$scope.tasks = response.tasks;
});
$scope.editTask = function(task) {
$scope.selectedTask = task;
};
$scope.removeRow = function(task) {
$scope.tasks.splice(task, 1);
};
$scope.addNewTask = function() {
//$scope.tasks.push({title :$scope.task1,description: $scope.description1});
$scope.tasks.push({title: $scope.task1, description: $scope.description1});
$scope.task1 = '';
$scope.description1 = '';
// $scope.tasks.push('dhsh');
};
});
/*
app.controller('addNewTaskCtrl', ['$scope', function($scope){
$scope.addNewTask=function(){
var task;
}
}]);*/
</script>
</body>
</html>

Your login page is rendering but what i see here is Class modal hide fade is not set.Try using class="modal" in login div instead of class="modal hide fade"

Related

Retain checkbox selection on click of previous and next in the bootstrap modal

I've a bootstrap modal which contains a table of users.
I can select a user from the table and on clicking 'save', the details of seleced user is displayed.
I'm displaying 10 users per page in the table of the modal.
However, if I select any user from page 1 and then click next to select some users from page 2 and click on 'save', my selection from page 1 is not retained.
I mean the checkbox is cleared on page 1, whenever I click on next or previous.
How do I retain this selection on my checkbox, even if I click on next or previous at any page?
Here's the snippet:
var currentPageNo = 0; // Keep track of currently displayed page
// Select button that is descendant of userList
$('#userList .prev-btn').click(function(){
userList(currentPageNo-10);
});
$('#userList .next-btn').click(function(){
userList(currentPageNo+10);
});
$('#adminList .prev-btn').click(function(){
adminList(currentPageNo-10);
});
$('#adminList .next-btn').click(function(){
adminList(currentPageNo+10);
});
function userList(pageNo) {
var resType="userList";
createTable(resType,pageNo);
}
function adminList(pageNo) {
var resType="adminList";
createTable(resType,pageNo);
}
function createTable(resType, pageNo) {
// Update global variable
currentPageNo = pageNo;
// Set visibility of the correct "prev" button:
$('#' + resType + ' .prev-btn').toggle(pageNo > 0);
// Ask one record more than needed, to determine if there are more records after this page:
$.getJSON("https://api.randomuser.me/?results=11&resType="+resType + "&pageIndex=" + pageNo, function(data) {
var $table = $('#' + resType + ' table');
$('tr:has(td)', $table).empty();
// Check if there's an extra record which we do not display,
// but determines that there is a next page
$('#' + resType + ' .next-btn').toggle(data.results.length > 10);
// Slice results, so 11th record is not included:
data.results.slice(0, 10).forEach(function (record, i) { // add second argument for numbering records
var json = JSON.stringify(record);
$table.append(
$('<tr>').append(
$('<td>').append(
$('<input>').attr('type', 'checkbox')
.addClass('selectRow')
.val(json),
(i+1+pageNo) // display row number
),
$('<td>').append(
$('<a>').attr('href', record.picture.thumbnail)
.addClass('imgurl')
.attr('target', '_blank')
.text(record.name.first)
),
$('<td>').append(record.dob)
)
);
});
// Show the prev and/or buttons
}).fail(function(error) {
console.log("**********AJAX ERROR: " + error);
});
}
var savedData = []; // The objects as array, so to have an order.
function saveData(){
var errors = [];
// Add selected to map
$('input.selectRow:checked').each(function(count) {
// Get the JSON that is stored as value for the checkbox
var obj = JSON.parse($(this).val());
// See if this URL was already collected (that's easy with Set)
if (savedData.find(record => record.picture.thumbnail === obj.picture.thumbnail)) {
errors.push(obj.name.first);
} else {
// Append it
savedData.push(obj);
}
});
refreshDisplay();
if (errors.length) {
alert('The following were already selected:\n' + errors.join('\n'));
}
}
function refreshDisplay() {
$('.container').html('');
savedData.forEach(function (obj) {
// Reset container, and append collected data (use jQuery for appending)
$('.container').append(
$('<div>').addClass('parent').append(
$('<label>').addClass('dataLabel').text('Name: '),
obj.name.first + ' ' + obj.name.last,
$('<br>'), // line-break between name & pic
$('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'),
$('<label>').addClass('dataLabel').text('Date of birth: '),
obj.dob, $('<br>'),
$('<label>').addClass('dataLabel').text('Address: '), $('<br>'),
obj.location.street, $('<br>'),
obj.location.city + ' ' + obj.location.postcode, $('<br>'),
obj.location.state, $('<br>'),
$('<button>').addClass('removeMe').text('Delete'),
$('<button>').addClass('top-btn').text('Swap with top'),
$('<button>').addClass('down-btn').text('Swap with down')
)
);
})
// Clear checkboxes:
$('.selectRow').prop('checked', false);
handleEvents();
}
function logSavedData(){
// Convert to JSON and log to console. You would instead post it
// to some URL, or save it to localStorage.
console.log(JSON.stringify(savedData, null, 2));
}
function getIndex(elem) {
return $(elem).parent('.parent').index();
}
$(document).on('click', '.removeMe', function() {
// Delete this from the saved Data
savedData.splice(getIndex(this), 1);
// And redisplay
refreshDisplay();
});
/* Swapping the displayed articles in the result list */
$(document).on('click', ".down-btn", function() {
var index = getIndex(this);
// Swap in memory
savedData.splice(index, 2, savedData[index+1], savedData[index]);
// And redisplay
refreshDisplay();
});
$(document).on('click', ".top-btn", function() {
var index = getIndex(this);
// Swap in memory
savedData.splice(index-1, 2, savedData[index], savedData[index-1]);
// And redisplay
refreshDisplay();
});
/* Disable top & down buttons for the first and the last article respectively in the result list */
function handleEvents() {
$(".top-btn, .down-btn").prop("disabled", false).show();
$(".parent:first").find(".top-btn").prop("disabled", true).hide();
$(".parent:last").find(".down-btn").prop("disabled", true).hide();
}
$(document).ready(function(){
$('#showExtForm-btn').click(function(){
$('#extUser').toggle();
});
$("#extUserForm").submit(function(e){
addExtUser();
return false;
});
});
function addExtUser() {
var extObj = {
name: {
title: "mr", // No ladies? :-)
first: $("#name").val(),
// Last name ?
},
dob: $("#dob").val(),
picture: {
thumbnail: $("#myImg").val()
},
location: { // maybe also ask for this info?
}
};
savedData.push(extObj);
refreshDisplay(); // Will show some undefined stuff (location...)
}
.parent {
background-color: #0000FF;
color: white;
border: 1px solid black;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#userList" onclick="userList(0)">User List</button>
<button class="btn btn-primary btn-sm" onclick="logSavedData()">Get Saved Data</button>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#adminList" onclick="adminList(0)">User Admin</button>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#extUser">Open External Form</button>
<div class="modal fade" id="userList" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">User List</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-bordered table-hover" id="datatable">
<tr>
<th>Select</th>
<th>Name</th>
<th>DOB</th>
</tr>
</table>
</div>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary prev-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary next-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
</div>
</div>
<hr/>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary btn-sm" onclick="saveData()">Save selected</button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary btn-sm close-less-modal" data-dismiss="modal">Close</button>
</div>
</div>
<br />
</div>
</div>
</div>
</div>
<div class="modal fade" id="adminList" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Admin List</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-bordered table-hover" id="datatable">
<tr>
<th>Select</th>
<th>Name</th>
<th>DOB</th>
</tr>
</table>
</div>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary prev-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary next-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
</div>
</div>
<hr/>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary btn-sm" onclick="saveData()">Save selected</button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary btn-sm close-less-modal" data-dismiss="modal">Close</button>
</div>
</div>
<br />
</div>
</div>
</div>
</div>
<div class="modal fade" id="extUser" role="dialog">
<div class="modal-dialog modal-lg">
<!-- External User-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add External User</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" id="extUserForm">
<div class="form-group">
<label class="control-label col-sm-3" for="name">Name:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="name" name="name" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="myImg">Image:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="myImg" name="myImg" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="dob">DOB:</label>
<div class="col-sm-8">
<input type="date" class="form-control" id="dob" name="dob" required>
</div>
</div>
<hr />
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
<button class="btn btn-primary btn-sm">Submit</button>
</div>
<div class="col-sm-3">
<button type="reset" class="btn btn-primary btn-sm">Reset</button>
</div>
<div class="col-sm-3">
<button type="button" class="btn btn-primary btn-sm close-external-modal" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="container"></div>
If you want the checkboxes to persist even when you move to another page, I would suggest that you actually keep those rows with checkboxes, but just hide them when moving to the next page.
The idea is that you never remove rows, but only add them when moving to a page you had not yet visited. But when going back to previous pages, you just make those 10 rows visible, and hide all others. That way you will even have a better user-experience, since those pages do not have to be requested from the server any more.
To achieve this, you just have to make a few changes in the first few lines of the creatTable function:
function createTable(resType, pageNo) {
// Update global variable
currentPageNo = pageNo;
// Set visibility of the correct "prev" button:
$('#' + resType + ' .prev-btn').toggle(pageNo > 0);
// *** See if we have that page already loaded
var $table = $('#' + resType + ' table');
// *** Count the rows already in the table, to see if we already have the page
var lastPageNo = $('tr:has(td)', $table).length - 1;
if (currentPageNo < lastPageNo) {
// *** We have the page: hide all rows, except those of that page
$('tr:has(td)', $table).hide().slice(currentPageNo, currentPageNo+10).show();
return;
}
// Otherwise make the request.
// Ask one record more than needed, to determine if there are more records after this page:
$.getJSON("https://api.randomuser.me/?results=11&resType="+resType + "&pageIndex=" + pageNo, function(data) {
//*** don't clear the table, but hide all rows, so they can be reused when paging back
$('tr:has(td)', $table).hide();
// Check if there's an extra record which we do not display,
// but determines that there is a next page
$('#' + resType + ' .next-btn').toggle(data.results.length > 10);
// ...etc ... etc
Here is the whole snippet:
var currentPageNo = 0; // Keep track of currently displayed page
// Select button that is descendant of userList
$('#userList .prev-btn').click(function(){
userList(currentPageNo-10);
});
$('#userList .next-btn').click(function(){
userList(currentPageNo+10);
});
$('#adminList .prev-btn').click(function(){
adminList(currentPageNo-10);
});
$('#adminList .next-btn').click(function(){
adminList(currentPageNo+10);
});
function userList(pageNo) {
var resType="userList";
createTable(resType,pageNo);
}
function adminList(pageNo) {
var resType="adminList";
createTable(resType,pageNo);
}
function createTable(resType, pageNo) {
// Update global variable
currentPageNo = pageNo;
// Set visibility of the correct "prev" button:
$('#' + resType + ' .prev-btn').toggle(pageNo > 0);
// *** See if we have that page already loaded
var $table = $('#' + resType + ' table');
// *** Count the rows already in the table, to see if we already have the page
var lastPageNo = $('tr:has(td)', $table).length - 1;
if (currentPageNo < lastPageNo) {
// *** We have the page: hide all rows, except those of that page
$('tr:has(td)', $table).hide().slice(currentPageNo, currentPageNo+10).show();
return;
}
// Otherwise make the request.
// Ask one record more than needed, to determine if there are more records after this page:
$.getJSON("https://api.randomuser.me/?results=11&resType="+resType + "&pageIndex=" + pageNo, function(data) {
//*** don't clear the table, but hide all rows, so they can be reused when paging back
$('tr:has(td)', $table).hide();
// Check if there's an extra record which we do not display,
// but determines that there is a next page
$('#' + resType + ' .next-btn').toggle(data.results.length > 10);
// Slice results, so 11th record is not included:
data.results.slice(0, 10).forEach(function (record, i) { // add second argument for numbering records
var json = JSON.stringify(record);
$table.append(
$('<tr>').append(
$('<td>').append(
$('<input>').attr('type', 'checkbox')
.addClass('selectRow')
.val(json),
(i+1+pageNo) // display row number
),
$('<td>').append(
$('<a>').attr('href', record.picture.thumbnail)
.addClass('imgurl')
.attr('target', '_blank')
.text(record.name.first)
),
$('<td>').append(record.dob)
)
);
});
}).fail(function(error) {
console.log("**********AJAX ERROR: " + error);
});
}
var savedData = []; // The objects as array, so to have an order.
function saveData(){
var errors = [];
// Add selected to map
$('input.selectRow:checked').each(function(count) {
// Get the JSON that is stored as value for the checkbox
var obj = JSON.parse($(this).val());
// See if this URL was already collected (that's easy with Set)
if (savedData.find(record => record.picture.thumbnail === obj.picture.thumbnail)) {
errors.push(obj.name.first);
} else {
// Append it
savedData.push(obj);
}
});
refreshDisplay();
if (errors.length) {
alert('The following were already selected:\n' + errors.join('\n'));
}
}
function refreshDisplay() {
$('.container').html('');
savedData.forEach(function (obj) {
// Reset container, and append collected data (use jQuery for appending)
$('.container').append(
$('<div>').addClass('parent').append(
$('<label>').addClass('dataLabel').text('Name: '),
obj.name.first + ' ' + obj.name.last,
$('<br>'), // line-break between name & pic
$('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'),
$('<label>').addClass('dataLabel').text('Date of birth: '),
obj.dob, $('<br>'),
$('<label>').addClass('dataLabel').text('Address: '), $('<br>'),
obj.location.street, $('<br>'),
obj.location.city + ' ' + obj.location.postcode, $('<br>'),
obj.location.state, $('<br>'),
$('<button>').addClass('removeMe').text('Delete'),
$('<button>').addClass('top-btn').text('Swap with top'),
$('<button>').addClass('down-btn').text('Swap with down')
)
);
})
// Clear checkboxes:
$('.selectRow').prop('checked', false);
handleEvents();
}
function logSavedData(){
// Convert to JSON and log to console. You would instead post it
// to some URL, or save it to localStorage.
console.log(JSON.stringify(savedData, null, 2));
}
function getIndex(elem) {
return $(elem).parent('.parent').index();
}
$(document).on('click', '.removeMe', function() {
// Delete this from the saved Data
savedData.splice(getIndex(this), 1);
// And redisplay
refreshDisplay();
});
/* Swapping the displayed articles in the result list */
$(document).on('click', ".down-btn", function() {
var index = getIndex(this);
// Swap in memory
savedData.splice(index, 2, savedData[index+1], savedData[index]);
// And redisplay
refreshDisplay();
});
$(document).on('click', ".top-btn", function() {
var index = getIndex(this);
// Swap in memory
savedData.splice(index-1, 2, savedData[index], savedData[index-1]);
// And redisplay
refreshDisplay();
});
/* Disable top & down buttons for the first and the last article respectively in the result list */
function handleEvents() {
$(".top-btn, .down-btn").prop("disabled", false).show();
$(".parent:first").find(".top-btn").prop("disabled", true).hide();
$(".parent:last").find(".down-btn").prop("disabled", true).hide();
}
$(document).ready(function(){
$('#showExtForm-btn').click(function(){
$('#extUser').toggle();
});
$("#extUserForm").submit(function(e){
addExtUser();
return false;
});
});
function addExtUser() {
var extObj = {
name: {
title: "mr", // No ladies? :-)
first: $("#name").val(),
// Last name ?
},
dob: $("#dob").val(),
picture: {
thumbnail: $("#myImg").val()
},
location: { // maybe also ask for this info?
}
};
savedData.push(extObj);
refreshDisplay(); // Will show some undefined stuff (location...)
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#userList" onclick="userList(0)">User List</button>
<button class="btn btn-primary btn-sm" onclick="logSavedData()">Get Saved Data</button>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#adminList" onclick="adminList(0)">User Admin</button>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#extUser">Open External Form</button>
<div class="modal fade" id="userList" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">User List</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-bordered table-hover" id="datatable">
<tr>
<th>Select</th>
<th>Name</th>
<th>DOB</th>
</tr>
</table>
</div>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary prev-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary next-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
</div>
</div>
<hr/>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary btn-sm" onclick="saveData()">Save selected</button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary btn-sm close-less-modal" data-dismiss="modal">Close</button>
</div>
</div>
<br />
</div>
</div>
</div>
</div>
<div class="modal fade" id="adminList" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Admin List</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-bordered table-hover" id="datatable">
<tr>
<th>Select</th>
<th>Name</th>
<th>DOB</th>
</tr>
</table>
</div>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary prev-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary next-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
</div>
</div>
<hr/>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary btn-sm" onclick="saveData()">Save selected</button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary btn-sm close-less-modal" data-dismiss="modal">Close</button>
</div>
</div>
<br />
</div>
</div>
</div>
</div>
<div class="modal fade" id="extUser" role="dialog">
<div class="modal-dialog modal-lg">
<!-- External User-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add External User</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" id="extUserForm">
<div class="form-group">
<label class="control-label col-sm-3" for="name">Name:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="name" name="name" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="myImg">Image:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="myImg" name="myImg" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="dob">DOB:</label>
<div class="col-sm-8">
<input type="date" class="form-control" id="dob" name="dob" required>
</div>
</div>
<hr />
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
<button class="btn btn-primary btn-sm">Submit</button>
</div>
<div class="col-sm-3">
<button type="reset" class="btn btn-primary btn-sm">Reset</button>
</div>
<div class="col-sm-3">
<button type="button" class="btn btn-primary btn-sm close-external-modal" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="container"></div>

ngResource is failing to load

I'm using ngResource with http to call the rest webservice that I made for the crud and I get this error http://errors.angularjs.org/1.4.8/$injector/modulerr?p0=myApp&p1=Error%3A%2…0yc%20(http%3A%2F%2Flocalhost%3A8088%2Fangular%2Fangular.min.js%3A20%3A274)
I put the angular js script reference properly but it's not working
this is my code:
var app = angular.module('myApp', ['ngResource']);
app.controller('StadeController', ['$scope', '$resource',function($scope,$resource) {
function fetchAllStades(){
$scope.stades = $resource('http://localhost:8088/stades'
).query(function(data){return data;});
};
fetchAllStades();
$scope.refresh = function(){
fetchAllStades();
};
$scope.create = function(){
Stade = $resource(
"http://localhost:8088/stades",
{},
{save: {method:'POST',isArray:false}}
);
var stade = {};
stade.id = $scope.stadeForm.id;
stade.name = $scope.stadeForm.description;
stade.phoneNo = $scope.stadeForm.checked;
$scope.Message = Stade.save(stade);
$scope.stadeForm.id = "";
$scope.stadeForm.description="";
$scope.stadeForm.checked="";
};
$scope.deleteRec = function(){
Stade = $resource(
"http://localhost:8088/stades/:id",
{},
{save: {method:'DELETE', params: {id: '#id'}}}
);
Stade.delete({id: $scope.stadeForm.id}).then(function successCallback(response) {
$scope.Message = response;
}, function errorCallback(response) {
});
$scope.stadeForm.id = "";
$scope.stadeForm.description="";
$scope.stadeForm.checked="";
};
$scope.update = function(){
Stade = $resource(
"http://localhost:8088/stades/:id",
{},
{save: {method:'PUT', params: {id: '#id'}}}
);
var stade = {};
stade.id = $scope.stadeForm.id;
stade.description = $scope.stadeForm.description;
stade.checked = $scope.stadeForm.checked;
$scope.Message = Stade.save({id: $scope.stadeForm.id}, stade);
$scope.stadeForm.id = "";
$scope.stadeForm.description="";
$scope.stadeForm.checked="";
};
}]);
<!DOCTYPE html>
<html lang="en">
<body ng-app="myApp">
<div ng-controller="StadeController">
<form name="stadeForm" >
<table class="table stripped">
<thead><tr><th>ID </th> <th>checked</th> <th>description</th></tr></thead>
<tbody><tr ng-repeat="row in stades">
<td><span ng-bind="row.id"></span></td>
<td><span ng-bind="row.description"></span></td>
<td><span ng-bind="row.checked"></span></td>
<td>
</tr> </tbody>
</table>
<p class="bg-info info-msg" id="info1">{{Message}}</p>
<div class="form-group" >
<label class=blue_font>description</label>
<input class=form-control type="text" id="description" ng-model="stadeForm.description" placeholder="description">
</div>
<div class="form-group" >
<label class=blue_font>checked</label>
<input class=form-control type="text" id="checked" ng-model="stadeForm.checked" placeholder="checked">
</div>
<div class="btn-wrapper">
<div class="row-gutter-5">
<div class="col-md-4 col-xs-6 col-sm-6">
<button class="btn btn_blue" type="button" data-ng-click="create()" id="Create" >Create</button>
</div>
<div class="col-md-4 col-xs-6 col-sm-6">
<button class="btn btn_blue" type="button" data-ng-click="refresh()" id="refresh">Refresh</button>
</div>
</div>
</div>
<div class="form-group" >
<label class=blue_font>ID</label>
<input class=form-control type="text" id="ID" ng-model="stadeForm.id" placeholder="ID">
</div>
<div class="btn-wrapper">
<div class="row-gutter-5">
<div class="col-md-4 col-xs-6 col-sm-6">
<button class="btn btn_blue" type="button" data-ng-click="deleteRec()" id="Delete" >Delete</button>
</div>
<div class="col-md-4 col-xs-6 col-sm-6">
<button class="btn btn_blue" type="button" data-ng-click="update()" id="Update">Update</button>
</div>
</div>
</div>
</form>
</div>
<script src="angular/angular.min.js"></script>
<script src="angular/angular-resource.min.js"></script>
<script src=app/app.js"></script>
<link rel="stylesheet" href="bootsrap/style.css">
<link rel="stylesheet" href="bootsrap/theme-default.css">
<link rel="stylesheet" href="bootsrap/theme-blue.css">
<link rel="stylesheet" href="bootsrap/bootstrap.min.css">
<link rel="stylesheet" href="bootsrap/custom.css">
</body>
</html>
I don't know why it's not working and I saw the previous posts that have problems like mine but it didn't work
Error on the line <script src=app/app.js"></script>. Open " is missing.
It should be <script src="app/app.js"></script>
<!DOCTYPE html>
<html lang="en">
<body ng-app="myApp">
<div ng-controller="StadeController">
<form name="stadeForm" >
<table class="table stripped">
<thead><tr><th>ID </th> <th>checked</th> <th>description</th></tr></thead>
<tbody><tr ng-repeat="row in stades">
<td><span ng-bind="row.id"></span></td>
<td><span ng-bind="row.description"></span></td>
<td><span ng-bind="row.checked"></span></td>
<td>
</tr> </tbody>
</table>
<p class="bg-info info-msg" id="info1">{{Message}}</p>
<div class="form-group" >
<label class=blue_font>description</label>
<input class=form-control type="text" id="description" ng-model="stadeForm.description" placeholder="description">
</div>
<div class="form-group" >
<label class=blue_font>checked</label>
<input class=form-control type="text" id="checked" ng-model="stadeForm.checked" placeholder="checked">
</div>
<div class="btn-wrapper">
<div class="row-gutter-5">
<div class="col-md-4 col-xs-6 col-sm-6">
<button class="btn btn_blue" type="button" data-ng-click="create()" id="Create" >Create</button>
</div>
<div class="col-md-4 col-xs-6 col-sm-6">
<button class="btn btn_blue" type="button" data-ng-click="refresh()" id="refresh">Refresh</button>
</div>
</div>
</div>
<div class="form-group" >
<label class=blue_font>ID</label>
<input class=form-control type="text" id="ID" ng-model="stadeForm.id" placeholder="ID">
</div>
<div class="btn-wrapper">
<div class="row-gutter-5">
<div class="col-md-4 col-xs-6 col-sm-6">
<button class="btn btn_blue" type="button" data-ng-click="deleteRec()" id="Delete" >Delete</button>
</div>
<div class="col-md-4 col-xs-6 col-sm-6">
<button class="btn btn_blue" type="button" data-ng-click="update()" id="Update">Update</button>
</div>
</div>
</div>
</form>
</div>
<script src="angular/angular.min.js"></script>
<script src="angular/angular-resource.min.js"></script>
<script src="app/app.js"></script>
<link rel="stylesheet" href="bootsrap/style.css">
<link rel="stylesheet" href="bootsrap/theme-default.css">
<link rel="stylesheet" href="bootsrap/theme-blue.css">
<link rel="stylesheet" href="bootsrap/bootstrap.min.css">
<link rel="stylesheet" href="bootsrap/custom.css">
</body>
</html>
var app = angular.module('myApp', ['ngResource']);
app.controller('StadeController', ['$scope', '$resource',function($scope,$resource) {
function fetchAllStades(){
$scope.stades = $resource('http://localhost:8088/stades'
).query(function(data){return data;});
};
fetchAllStades();
$scope.refresh = function(){
fetchAllStades();
};
$scope.create = function(){
Stade = $resource(
"http://localhost:8088/stades",
{},
{save: {method:'POST',isArray:false}}
);
var stade = {};
stade.id = $scope.stadeForm.id;
stade.name = $scope.stadeForm.description;
stade.phoneNo = $scope.stadeForm.checked;
$scope.Message = Stade.save(stade);
$scope.stadeForm.id = "";
$scope.stadeForm.description="";
$scope.stadeForm.checked="";
};
$scope.deleteRec = function(){
Stade = $resource(
"http://localhost:8088/stades/:id",
{},
{save: {method:'DELETE', params: {id: '#id'}}}
);
Stade.delete({id: $scope.stadeForm.id}).then(function successCallback(response) {
$scope.Message = response;
}, function errorCallback(response) {
});
$scope.stadeForm.id = "";
$scope.stadeForm.description="";
$scope.stadeForm.checked="";
};
$scope.update = function(){
Stade = $resource(
"http://localhost:8088/stades/:id",
{},
{save: {method:'PUT', params: {id: '#id'}}}
);
var stade = {};
stade.id = $scope.stadeForm.id;
stade.description = $scope.stadeForm.description;
stade.checked = $scope.stadeForm.checked;
$scope.Message = Stade.save({id: $scope.stadeForm.id}, stade);
$scope.stadeForm.id = "";
$scope.stadeForm.description="";
$scope.stadeForm.checked="";
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<body ng-app="myApp">
<div ng-controller="StadeController">
<form name="stadeForm" >
<table class="table stripped">
<thead><tr><th>ID </th> <th>checked</th> <th>description</th></tr></thead>
<tbody><tr ng-repeat="row in stades">
<td><span ng-bind="row.id"></span></td>
<td><span ng-bind="row.description"></span></td>
<td><span ng-bind="row.checked"></span></td>
<td>
</tr> </tbody>
</table>
<p class="bg-info info-msg" id="info1">{{Message}}</p>
<div class="form-group" >
<label class=blue_font>description</label>
<input class=form-control type="text" id="description" ng-model="stadeForm.description" placeholder="description">
</div>
<div class="form-group" >
<label class=blue_font>checked</label>
<input class=form-control type="text" id="checked" ng-model="stadeForm.checked" placeholder="checked">
</div>
<div class="btn-wrapper">
<div class="row-gutter-5">
<div class="col-md-4 col-xs-6 col-sm-6">
<button class="btn btn_blue" type="button" data-ng-click="create()" id="Create" >Create</button>
</div>
<div class="col-md-4 col-xs-6 col-sm-6">
<button class="btn btn_blue" type="button" data-ng-click="refresh()" id="refresh">Refresh</button>
</div>
</div>
</div>
<div class="form-group" >
<label class=blue_font>ID</label>
<input class=form-control type="text" id="ID" ng-model="stadeForm.id" placeholder="ID">
</div>
<div class="btn-wrapper">
<div class="row-gutter-5">
<div class="col-md-4 col-xs-6 col-sm-6">
<button class="btn btn_blue" type="button" data-ng-click="deleteRec()" id="Delete" >Delete</button>
</div>
<div class="col-md-4 col-xs-6 col-sm-6">
<button class="btn btn_blue" type="button" data-ng-click="update()" id="Update">Update</button>
</div>
</div>
</div>
</form>
</div>
<script src="angular/angular.min.js"></script>
<script src="angular/angular-resource.min.js"></script>
<script src=app/app.js"></script>
<link rel="stylesheet" href="bootsrap/style.css">
<link rel="stylesheet" href="bootsrap/theme-default.css">
<link rel="stylesheet" href="bootsrap/theme-blue.css">
<link rel="stylesheet" href="bootsrap/bootstrap.min.css">
<link rel="stylesheet" href="bootsrap/custom.css">
</body>
</html>

Display comments in comment box with AngularJS - ng-repeat inside another ng-repeat using API JSON data

I'm simply trying to display comments that users put within a comment box. However, I'm having issues because it's within an ng-repeat directive. Let me show so you can better understand visually:
<!DOCTYPE html>
<html lang="en" ng-app="MyApp">
<head>
<meta charset="UTF-8">
<title>Nuvi Interview Code Project</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="stylesheet.css">
</head>
<body ng-controller="HomeController">
<div class="container-fluid">
<h1>Nuvi Interview Code Project</h1>
<form class="form-inline well well-sm clearfix">
<span class="glyphicon glyphicon-search"></span>
<input type="text" placeholder="Search" class="form-control" ng-model="search">
</form>
<div class="row">
<div class="col-sm-6" ng-repeat="actor in data | filter:search">
<div class="well well-sm">
<div class="row">
<div class="col-md-6">
<img ng-src="{{actor.actor_avator}}" class="img-rounded img-responsive well-image pull-left">
<h3 class="name" data-toggle="modal" data-target="#actor-info" ng-click="changeActiveActor(actor)">{{actor.actor_name}}</h3>
<hr>
<p ng-repeat="say in activity_comments">{{say}}</p>
<div>{{actor.activity_comments}} Comments {{actor.activity_likes}} likes {{actor.activity_shares}} shares</div>
<br>
<input type="text" class="form-control" placeholder="Write a comment..." ng-model="comment">
<button class="btn btn-default" ng-click="postComment($index, comment)">Post Comment</button>
</div>
<div class="col-md-6">
<p class="pull-right"><strong>{{actor.provider}} </strong></p>
<p><strong>Post</strong></p>
<h5>{{actor.activity_message}}</h5>
<br><br><br><br><br>
<button ng-click="countUp($index)" type="button" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-thumbs-up"></span> Like
</button>
<button ng-click="countDown($index)" type="button" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-thumbs-down"></span> Unlike
</button>
</div>
</div>
</div>
</div>
</div>
<div class="modal" id="actor-info">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h2>{{activeActor.actor_name}}</h2>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-8 col-xs-offset-2">
<img ng-src="{{activeActor.actor_avator}}" class="img-rounded img-responsive">
</div>
</div>
<div class="row top-buffer">
<div class="col-md-6">
<p>Message: {{activeActor.activity_message}}</p>
<p><strong>Username:</strong> {{activeActor.actor_username}}</p>
<p><strong>Date:</strong> {{activeActor.activity_date}}</p>
<p><strong>Comment:</strong> {{activeActor.activity_comments}}</p>
<p><strong>Likes:</strong> {{activeActor.activity_likes}}</p>
<p><strong>Sentiment:</strong> {{activeActor.activity_sentiment}}</p>
<p><strong>Shares:</strong> {{activeActor.activity_shares}}</p>
<p><strong>ID:</strong> {{activeActor.id}}</p>
<p><strong>Provider:</strong> {{activeActor.provider}}</p>
</div>
<div class="col-xs-12">
<p></p>
<button class="btn btn-danger pull-right" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END OF MODAL -->
<hr>
<h6 class="pull-right">Coded by Saia Fonua</h6>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="app.js"></script>
</body>
</html>
Here is my app.js:
var app = angular.module("MyApp", []);
app.controller("HomeController", ["$scope", "$http", function($scope, $http) {
$scope.data = [];
$scope.search = "";
$scope.comment = "";
$scope.activeActor = {};
$scope.changeActiveActor = function(index) {
$scope.activeActor = index;
}
$scope.postComment = function(index, comment) {
console.log('comment ', comment);
//$scope.data[index].comments = [];
$scope.data[index].comments.push(comment);
console.log($scope.data[index]);
}
$scope.countUp = function(index) {
$scope.data[index].activity_likes++;
}
$scope.countDown = function(index) {
$scope.data[index].activity_likes--;
}
$http.get("https://nuvi-challenge.herokuapp.com/activities").then(function(response) {
console.log(response.data);
$scope.data = response.data;
})
}])
Can someone please help me to get the comments to display. When you start playing around with it, you'll see why it's harder than the problem sounds!
You have some problems with this line
<p ng-repeat="say in activity_comments">{{say}}</p>
As you are adding the comments to
$scope.data[index].comments.push(comment);
They would be reached by the actor.comments object
<p ng-repeat="say in actor.comments">{{say}}</p>

Opening a DIV in the HTML as Modal in AngularJS

Learning some AngularJS here...
I have an Angular application which connects to an ASP.Net WebAPI.
I am trying to have a DIV inside my HTML open as a modal window.
My HTML looks as follows:
<div class="container" style="padding-top:20px;">
<div ng-app="vehicleApp" data-ng-controller="testingController" class="container">
<div ng-show="error" class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<p>{{ error }}</p>
</div>
<div class="modal fade" id="vehicleModel" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">X</button>
<h4 class="modal-title" id="myModalLabel" ng-hide="editMode">Add vehicle</h4>
<h4 class="modal-title" id="myModalLabel" ng-show="editMode">Edit vehicle: {{ vehicle.Id }}</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form" name="addvehicleform">
<div class="form-group">
<label for="title" class="col-sm-3 control-label">vehicle Name</label>
<div class="col-sm-7">
<input type="text" data-ng-model="vehicle.Name" class="form-control" id="vehiclename" placeholder="vehicle Name" required title="Enter your vehicle Name" />
</div>
</div>
<div class="form-group">
<label for="title" class="col-sm-3 control-label">Identification Account</label>
<div class="col-sm-7">
<input type="number" data-ng-model="vehicle.vehicleIdentificationAccountId" class="form-control" id="vehicleIdentificationAccountId" placeholder="vehicle Identification Account" required title="Enter your Identification Account" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-7">
<span data-ng-hide="editMode">
<input type="submit" value="Add" ng-disabled="addvehicleform.$invalid" data-ng-click="add()" class="btn btn-primary normal-button" />
</span>
<span data-ng-show="editMode">
<input type="submit" value="Update" ng-disabled="addvehicleform.$invalid" data-ng-click="update()" class="btn btn-primary normal-button" />
</span>
<input type="button" value="Cancel" data-ng-click="cancel()" class="btn btn-primary" />
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<h1>Vehicle List</h1>
<p><a data-ng-click="showadd()" href="javascript:;" class="btn btn-primary">Add New vehicle</a></p>
<table class="table table-striped table-bordered table-hover table-condensed">
<thead>
<tr>
<th>Vehicle ID</th>
<th>Name</th>
<th>Identification Account</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr data-ng-hide="agencies || agencies.length > 0">
<td colspan="4">
<div class="text-center text-warning">
<strong>No Agencies Retrieved</strong>
</div>
</td>
</tr>
<tr data-ng-repeat="vehicle in agencies">
<td>{{vehicle.Id}}</td>
<td>{{vehicle.Name}}</td>
<td>{{vehicle.vehicleIdentificationAccountId}}</td>
<td>
<a data-ng-click="get(vehicle)" href=""><span class="glyphicon glyphicon-open"></span>View</a>
<a data-ng-click="edit(vehicle)" href=""><span class="glyphicon glyphicon-edit"></span>Edit</a>
<a data-ng-click="showConfirm(vehicle)" href=""><span class="glyphicon glyphicon-remove-circle"></span>Delete</a>
</td>
</tr>
</tbody>
</table>
<hr />
<div class="modal fade" id="viewModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">X</button>
<h4 class="modal-title" id="myModalLabel">View vehicle Detail</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form" name="viewuser">
<div class="form-group">
<label for="ID" class="col-sm-3 control-label">ID</label>
<div class="col-sm-7">
{{vehicle.Id}}
</div>
</div>
<div class="form-group">
<label for="Name" class="col-sm-3 control-label">Name</label>
<div class="col-sm-7">
{{vehicle.Name}}
</div>
</div>
<div class="form-group">
<label for="vehicleIdentificationAccountId" class="col-sm-3 control-label">Identification Account</label>
<div class="col-sm-7">
{{vehicle.vehicleIdentificationAccountId}}
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="confirmModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">X</button>
<h4 class="modal-title" id="myModalLabel">Confirm</h4>
</div>
<div class="modal-body">
Are you sure you want to delete vehicle: {{ vehicle.Name}}?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-ng-click="delete()" style="width:100px;">Ok</button>
<button type="button" class="btn btn-primary" data-dismiss="modal" style="width:100px;">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</div>
testingController.js
'use strict';
app.controller('testingController', function ($scope, testingDataService, $modal) {
$scope.vehicles = [];
$scope.vehicle = null;
$scope.editMode = false;
// Get vehicle
$scope.get = function () {
$scope.vehicle = this.vehicle;
$('#viewModal').modal('show');
};
//get all vehicles
$scope.getAll = function () {
testingDataService.getvehicleList().success(function (data) {
$scope.vehicles = data;
}).error(function (data) {
$scope.error = "An Error has occured while Loading vehicles! " + data.ExceptionMessage;
});
};
// add vehicle
$scope.add = function () {
var currentvehicle = this.vehicle;
if (currentvehicle != null && currentvehicle.Name != null && currentvehicle.vehicleIdentificationAccountId!= null) {
testingDataService.addvehicle(currentvehicle).success(function (data) {
$scope.addMode = false;
currentvehicle = data;
$scope.vehicles.push(currentvehicle);
//reset form
$scope.vehicle = null;
$('#vehicleModel').modal('hide');
}).error(function (data) {
$scope.error = "An Error has occured while Adding vehicle! " + data.ExceptionMessage;
});
}
};
//edit vehicle
$scope.edit = function () {
$scope.vehicle = this.vehicle;
$scope.editMode = true;
$('#vehicleModel').modal('show');
};
//update vehicle
$scope.update = function () {
var currentvehicle = this.vehicle;
testingDataService.updatevehicle(currentvehicle).success(function (data) {
currentvehicle.editMode = false;
$('#vehicleModel').modal('hide');
}).error(function (data) {
$scope.error = "An Error has occured while Updating vehicle! " + data.ExceptionMessage;
});
};
// delete
$scope.delete = function () {
currentvehicle = $scope.vehicle;
testingDataService.deletevehicle(currentvehicle).success(function (data) {
$('#confirmModal').modal('hide');
$scope.vehicles.pop(currentvehicle);
}).error(function (data) {
$scope.error = "An Error has occured while Deleting vehicle! " + data.ExceptionMessage;
$('#confirmModal').modal('hide');
});
};
//Modal popup events
$scope.showadd = function () {
$scope.vehicle = null;
$scope.editMode = false;
$('#vehicleModel').modal({ backdrop: 'static' });
$('#vehicleModel').modal('show');
};
$scope.showedit = function () {
$('#vehicleModel').modal({ backdrop: 'static' });
$('#vehicleModel').modal('show');
};
$scope.showConfirm = function (data) {
$scope.vehicle = data;
$('#confirmModal').modal('show');
};
$scope.cancel = function () {
$scope.vehicle = null;
$('#vehicleModel').modal('hide');
}
// initialize your users data
$scope.getAll();
});
Basically when I click on the Add New Vehicle button, the console says:
ReferenceError: $ is not defined
on the line in the controller where it is supposed to show the modal:
$('#vehicleModel').modal({ backdrop: 'static' });
I am a bit lost on how to resolve this.
Appreciate any insight.
P.S. The data loads fine when this HTML view is loaded up. I also added a console.log inside the
$scope.showadd = function (){
console.log('Test');
};
and that is logged properly in the console. So totally lost right now...
Update:
Did a little more investigation. I issued in Chrome console the command:
$('#vehicleModel')
and it showed me the div with the id=vehicleModel.
I would argue that you should probably be using Angular UI Bootstrap to create your modal dialogs. Here is the link.
Here is a cut down version of how to open a modal using Angular UI Bootrstrap:
$scope.open = function (vehicle) {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
resolve: {
items: function () {
return $scope.items;
}
}
});
};
MODAL CONTENT
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">Modal!</h3>
</div>
<div class="modal-body">
<div >Body</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="$close('awesome')">OK</button>
<button class="btn btn-warning" ng-click="$dismiss('nah')">Cancel</button>
</div>
</script>
HTML
<a data-ng-click="open(vehicle)" href=""><span class="glyphicon glyphicon-open"></span>View</a>
You're trying to grab your element the jQuery way. $ is reserved in Angular. try using:
angular.element('div').modal({ backdrop: 'static' });
where 'div' is whatever your actual tag name is, and traverse the DOM for it...
EDIT: from https://docs.angularjs.org/error/jqLite/nosel
In order to resolve this error, rewrite your code to only use tag name selectors and manually traverse the DOM using the APIs provided by jqLite.
Alternatively, you can include a full version of jQuery, which Angular
will automatically use and that will make all selectors available.
You can code like this:
// Pre-fetch an external template populated with a custom scope
var myOtherModal = $modal({scope: $scope, template: 'modal/docs/modal.demo.tpl.html', show: false});
// Show when some event occurs (use $promise property to ensure the template has been loaded)
$scope.showModal = function() {
myOtherModal.$promise.then(myOtherModal.show);
};

AngularJS: Value from Page Not Showing in Modal on Click

I have a button (link) on a modal that when clicked (copySummaryToTask($event)) is supposed to copy data from the page's $scope element (thisRequest) into the modal's $scope element (nTask). It copies the correct data into the $scope but the data doesn't appear in the modal even though I am using $scope.$apply();
Here's the plunkr.
Here's my controller:
var myApp = angular.module('myApp', []);
myApp.controller('MainController', function($scope){
$scope.NewTaskPane = false;
$scope.thisRequest = {
ID: 543,
Title: 'Create This Wonderful SharePoint 2013 SPA',
Request_Summary: "Rule fruit and under female she'd every signs creepeth good Night, fly lesser they're be green cattle and living tree also spirit us years two. Seasons he good under creepeth fifth air is. For morning. It creeping multiply from, saying.",
Request_Type: 'Web'
};
$scope.Tasks = [
{ID: 20, Title: 'Prototype App', Assigned_To: 'Wayne, Bruce', Status: 'Completed', TOT: 4.5},
{ID: 21, Title: 'Develop App CSS', Assigned_To: 'Prince, Diana', Status: 'Completed', TOT: 6}
];
$scope.addNewTask = function($event){
$event.preventDefault();
$scope.NewTaskPane = true;
$scope.nTask = {
ID: $scope.Tasks.length + 1,
Request_ID: $scope.thisRequest.ID,
Title: $scope.thisRequest.Title,
Status: 'Assigned',
Resource_Instructions: ''
};
};
$scope.copySummaryToTask = function($event){
$event.preventDefault();
//alert($scope.thisRequest.Request_Summary);
$scope.nTask.Resource_Instructions = $scope.thisRequest.Request_Summary;
if (!$scope.$$phase) { $scope.$apply(); }
} // end copySummaryToTask fn
}); // end main controller
and here's the view:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link data-require="bootstrap-css#3.1.1" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<script data-require="angular.js#*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script data-require="jquery#*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="bootstrap#*" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<div id="overlay" data-ng-show="NewTaskPane">
<div class ="preference_form wModal" id="frmPreference">
<form name="frmNewTask" ng-submit="saveNewTask($event)">
<span class="close-modal">
close
</span>
<h1>New Task</h1>
<div class="row">
<div class="form-group col-lg-12">
<label for="description">Task Title:</label>
<input type="text" class="form-control" name="Title" ng-model="nTask.Title">
</div>
</div>
<div class="row">
<div class="form-group col-lg-12">
<label>Additional Instructions for Resource:</label>
<textarea class="form-control" rows="5">{{ntask.Resource_Instructions}}</textarea>
<button class="btn btn-link" style="float:right;" ng-click="copySummaryToTask($event)">Copy Customer Request Summary.</button>
</div>
</div>
<div class="frmElementSubmit">
<input type="button" class="btn btn-default" value="CANCEL" ng-click="NewTaskPane = false" />
<input type="submit" class="btn btn-primary" value="SAVE" ng-click="NewTaskPane = false" />
</div>
</form>
<pre>{{nTask | json}}</pre>
</div>
</div>
<div class="frmFull_Page">
<h1 class="frmTitle">Edit Request</h1>
<div class="frmBar clr-purple">
<h3>Request Information</h3>
</div>
<div class="frm_pane">
<div class="row">
<form name="EditSapForm" role="form">
<!-- ID / TITLE -->
<div class="row">
<div class="form-group col-lg-3">
<label for="req_id">Request ID:</label>
<input type="text" class="form-control" name="ID" ng-model="thisRequest.ID" disabled="disabled">
</div>
<div class="form-group col-lg-9">
<label for="title">Title:</label>
<input type="text" class="form-control" id="Title" ng-model="thisRequest.Title">
</div>
</div>
<!-- WORK SUMMARY -->
<div class="row">
<div class="form-group col-lg-12">
<label>Work Summary:</label>
<textarea name="Request_Summary" class="form-control" rows="5" ng-model="thisRequest.Request_Summary"></textarea>
</div>
</div>
<!-- WORK TASKS*** -->
<div class="row">
<div class="form-group col-lg-12">
<div class="row">
<div class="form-group col lg-12" style="margin-left:16px;">
<label>Work Tasks [{{Tasks.length}}]</label>
<table class="table table-striped" style="width:90%; margin:5px auto;">
<tr>
<th>ID</th>
<th>TITLE</th>
<th>ASSIGNED TO:</th>
<th>STATUS</th>
<th>TOT</th>
<th> </th>
</tr>
<tr ng-hide="Tasks.length">
<td colspan="6"><b>No Tasks Found!</b></td>
</tr>
<tr ng-repeat="task in Tasks">
<td>{{task.ID}}</td>
<td>{{task.Title}}</td>
<td>{{task.Assigned_To}}</td>
<td>{{task.Status}}</td>
<td>{{task.TOT}}</td>
<td>edit</td>
</tr>
<tr>
<td colspan="6"><a ng-click="addNewTask($event)">Add New Task</a></td>
</tr>
</table>
</div>
</div>
</div>
</div>
<!-- SUBMIT BUTTON*** -->
<div class="row" style="margin-top:30px;">
<div class="form-actions col-lg-12">
<button type="submit" class="btn btn-primary">SUBMIT</button>
</div>
</div>
</form>
</div> <!-- end row -->
</div> <!-- end frm_pane -->
</div> <!-- end frmFull_Page-->
</body>
</html>
There's a typo in your view:
<textarea class="form-control" rows="5">{{ntask.Resource_Instructions}}</textarea>
... where ntask should be nTask. Once you fix it, you won't need the $scope.apply():
$scope.copySummaryToTask = function($event){
$event.preventDefault();
$scope.nTask.Resource_Instructions = $scope.thisRequest.Request_Summary;
} // end copySummaryToTask fn
Replace
<textarea class="form-control" rows="5">{{ntask.Resource_Instructions}}</textarea>
With
<textarea class="form-control" rows="5" ng-model="nTask.Resource_Instructions"></textarea>
This will do it, plus capture any new text added by the user.

Resources