Uncaught ReferenceError: $scope is not defined - AngularJS - javascript

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.

Related

update the data dynamically in AngularJS

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.

How to change the div after user login

I am building a website and i wish to make a single page application. Iam using nodejs as a backend and angular as a frontend. The thing iam stuck up is i want to show a particular div when user is not logged in, on the event of logging in the other div should be shown. What is the best way to make it happen.
As per my knowledge i have used ng-if as the attribute of both the div which i want to replace each other. I had a angular function for verifying the logged in sesssion with a name isloggedin().
so i used <div ng-if="!checkLoggedin()"> in one div and <div ng-if="checkLoggedin()"> in other div.
So on the first request the page is not logged in and the conditions works as it should. But after i logged in the from the second is not showing up.
Is it something i wrongly expect to happen or is there any other to make this happen. I had check the value of the function and it has data in one condition and 0 in other condition. Am i wrong somewhere.
Added the conditional code.
var checkLoggedin = function ($q, $timeout, $http, $location, $rootScope) {
var deferred = $q.defer();
$http({
method: 'GET',
url: "http://localhost:3000/loggedin"
}).success(function (user) {
if (user !== '0') {
$rootScope.message = 'You are log in.';
$timeout(deferred.resolve, 0);
deferred.resolve();
$location.url('/home');
} else {
$rootScope.message = 'You need to log in.';
$timeout(function () {
deferred.reject();
}, 0);
deferred.reject();
$location.url('/login');
};
});
Here is the form code.
<form action="/#/home" ng-submit="login(user)">
<div class="form-group">
<div class="input-group input-group-in ui-no-corner no-border bordered-bottom bg-none">
<div class="input-group-addon"><i class="fa fa-envelope text-muted"></i></div>
<input class="form-control" placeholder="email" ng-model="user.email">
</div>
</div><!-- /.form-group -->
<div class="form-group">
<div class="input-group input-group-in ui-no-corner no-border bordered-bottom bg-none">
<div class="input-group-addon"><i class="fa fa-lock text-muted"></i></div>
<input type="password" class="form-control" placeholder="Password" ng-model="user.password">
<div class="input-group-addon"><small>Forgot?</small></div>
</div>
</div><!-- /.form-group -->
<div class="form-group">
<div class="row">
<div class="col-md-6">
<div class="nice-checkbox nice-checkbox-inline">
<input type="checkbox" name="rememberSignIn1" id="rememberSignIn">
<label for="rememberSignIn1">Remember</label>
</div>
</div><!-- /.cols -->
<div class="col-md-6">
<button type="submit" class="btn btn-sm btn-block btn-info" style="margin-top:5px" >SUBMIT</button>
</div><!-- /.cols -->
</div><!-- /.row -->
</div><!-- /.form-group -->
</form><!-- /form -->
</div><!-- /.panel-body -->
As I see, the blocks
<div ng-if="!checkLoggedin()">
and
<div ng-if="checkLoggedin()">
will be executed on DOM load (page load). So there is no chance for the model to update. The right approach here will be to use a scope variable in the if blocks as
<div ng-if="isLoggedIn"> ... <div ng-if="!isLoggedIn">
and to update the variable's value in the success handler of the service call, say,
var checkLoggedin = function ($q, $timeout, $http, $location, $rootScope) {
var deferred = $q.defer();
$http({
method: 'GET',
url: "http://localhost:3000/loggedin"
}).success(function (user) {
if (user !== '0') {
// set value here
$rootScope.isLoggedIn = true;
$rootScope.message = 'You are log in.';
$timeout(deferred.resolve, 0);
deferred.resolve();
$location.url('/home');
} else {
$rootScope.message = 'You need to log in.';
$timeout(function () {
deferred.reject();
}, 0);
deferred.reject();
$location.url('/login');
};
});
This way we can be sure that the model has updated values and the right if block will be added to DOM.
Your approach is correct, but may be you have not defined checkLoggedin() properly or may be you used in wrong way.
You can approach it with different way also,
Apply ng-if condition on ng-model variable,
<label> User Name </label>
<input ng-model="username" />
So here you can add condition on username, like:-
<div ng-if="username !== 'null' || 'undefined'"> If username fielld is touched </div>
<div ng-if="username === 'null' || 'undefined'"> If username field is not touched </div>

I cannot save data from angular to backend laravel database

I am passing form input from angular to laravel view api. But data cannot be saved in the database. I am getting the following error messages in the console:
error: [ngRepeat:dupes] http://errors.angularjs.org/1.5.0/ngRepeat/dupes?p0=app%20in%20apps&p1=string%3A%3C&p2=%3C
at Error (native)
at http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:6:416
at http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:292:254
at http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:137:302
at m.$digest (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:138:399)
at m.$apply (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:141:341)
at g (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:94:139)
at t (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:98:260)
at XMLHttpRequest.u.onload (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:99:297)(anonymous function) # angular.js:13236
apps.js:28 0
http://localhost/myapp/public/api/apps Failed to load resource: the server responded with a status of 500 (Internal Server Error)
I also get laravel errors:
<span class="exception_title"><abbr title="Illuminate\Database\QueryException">QueryException</abbr> in <a title="C:\xampp\htdocs\dukamart\vendor\laravel\framework\src\Illuminate\Database\Connection.php line 651" ondblclick="var f=this.innerHTML;this.innerHTML=this.title;this.title=f;">Connection.php line 651</a>:</span>
span class="exception_message">SQLSTATE[23000]: Integrity constraint violation: 1048 Column associated with input values.
I have checked my laravel controller seem to be fine. I am posting data from a popup form.
employeeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Employee;
class Employees extends Controller
{
//
public function index($id = null) {
if ($id == null) {
return Employee::orderBy('id', 'asc')->get();
} else {
return $this->show($id);
}
}
public function store(Request $request) {
$employee = new Employee;
$employee->name = $request->input('name');
$employee->email = $request->input('email');
$employee->contact_number = $request->input('contact_number');
$employee->position = $request->input('position');
$employee->save();
return 'Employee record successfully created with id ' . $employee->id;
}
//My angular controller
app.controller('employeesController', function($scope, $http, API_URL) {
//retrieve employees listing from API
$http.get(API_URL + "employees")
.success(function(response) {
$scope.employees = response;
});
//show modal form
$scope.toggle = function(modalstate, id) {
$scope.modalstate = modalstate;
switch (modalstate) {
case 'add':
$scope.form_title = "Add New Employee";
break;
case 'edit':
$scope.form_title = "Employee Detail";
$scope.id = id;
$http.get(API_URL + 'employees/' + id)
.success(function(response) {
console.log(response);
$scope.employee = response;
});
break;
default:
break;
}
console.log(id);
$('#myModal').modal('show');
}
//save new record / update existing record
$scope.save = function(modalstate, id) {
var url = API_URL + "employees";
//append Employee id to the URL if the form is in edit mode
if (modalstate === 'edit'){
url += "/" + id;
}
$http({
method: 'POST',
url: url,
data: $.param($scope.employee),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
console.log(response);
location.reload();
}).error(function(response) {
console.log(response);
alert('This is embarassing. An error has occured. Please check the log for details');
});
}
//delete record
$scope.confirmDelete = function(id) {
var isConfirmDelete = confirm('Are you sure you want this record?');
if (isConfirmDelete) {
$http({
method: 'DELETE',
url: API_URL + 'employees/' + id
}).
success(function(data) {
console.log(data);
location.reload();
}).
error(function(data) {
console.log(data);
alert('Unable to delete');
});
} else {
return false;
}
}
});
When I click to save the data, I am getting an error message I had setup in employeeController.js controller
$http({
method: 'POST',
url: url,
data: $.param($scope.hotel),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
console.log(response);
location.reload();
}).error(function(response) {
console.log(response);
alert('This is embarassing. An error has occured. Please check the log for details');
});
}
This my app.js
var app = angular.module(employees, [])
.constant('API_URL', 'http://localhost/myapp/public/api/');
My routes.php
Route::get('/api/v1/employees/{id?}', 'Employees#index');
Route::post('/api/v1/employees', 'Employees#store');
Route::post('/api/v1/employees/{id}', 'Employees#update');
Route::post('/api/v1/employees/update/{id}',['as'=>'update','uses'=> 'Employees#update']);
Route::delete('/api/v1/employees/{id}', 'Employees#destroy');
What could be the cause of this? Please help. I have tried to solve this for 3 days without success.
My View in resources/views/employees/employee.php
<!DOCTYPE html>
<html lang="en-US" ng-app="employeeRecords">
<head>
<title>Laravel 5 AngularJS CRUD Example</title>
<!-- Load Bootstrap CSS -->
<link href="<?= asset('css/bootstrap.min.css') ?>" rel="stylesheet">
</head>
<body>
<h2>Employees Database</h2>
<div ng-controller="employeesController">
<!-- Table-to-load-the-data Part -->
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Contact No</th>
<th>Position</th>
<th><button id="btn-add" class="btn btn-primary btn-xs" ng-click="toggle('add', 0)">Add New Employee</button></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees">
<td>{{ employee.id }}</td>
<td>{{ employee.name }}</td>
<td>{{ employee.email }}</td>
<td>{{ employee.contact_number }}</td>
<td>{{ employee.position }}</td>
<td>
<button class="btn btn-default btn-xs btn-detail" ng-click="toggle('edit', employee.id)">Edit</button>
<button class="btn btn-danger btn-xs btn-delete" ng-click="confirmDelete(employee.id)">Delete</button>
</td>
</tr>
</tbody>
</table>
<!-- End of Table-to-load-the-data Part -->
<!-- Modal (Pop up when detail button clicked) -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">{{form_title}}</h4>
</div>
<div class="modal-body">
<form name="frmEmployees" class="form-horizontal" novalidate="">
<div class="form-group error">
<label for="inputEmail3" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control has-error" id="name" name="name" placeholder="Fullname" value="{{name}}"
ng-model="employee.name" ng-required="true">
<span class="help-inline"
ng-show="frmEmployees.name.$invalid && frmEmployees.name.$touched">Name field is required</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9">
<input type="email" class="form-control" id="email" name="email" placeholder="Email Address" value="{{email}}"
ng-model="employee.email" ng-required="true">
<span class="help-inline"
ng-show="frmEmployees.email.$invalid && frmEmployees.email.$touched">Valid Email field is required</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Contact Number</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="contact_number" name="contact_number" placeholder="Contact Number" value="{{contact_number}}"
ng-model="employee.contact_number" ng-required="true">
<span class="help-inline"
ng-show="frmEmployees.contact_number.$invalid && frmEmployees.contact_number.$touched">Contact number field is required</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Position</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="position" name="position" placeholder="Position" value="{{position}}"
ng-model="employee.position" ng-required="true">
<span class="help-inline"
ng-show="frmEmployees.position.$invalid && frmEmployees.position.$touched">Position field is required</span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btn-save" ng-click="save(modalstate, id)" ng-disabled="frmEmployees.$invalid">Save changes</button>
</div>
</div>
</div>
</div>
</div>
<!-- Load Javascript Libraries (AngularJS, JQuery, Bootstrap) -->
<script src="<?= asset('app/lib/angular/angular.min.js') ?>"></script>
<script src="<?= asset('js/jquery.min.js') ?>"></script>
<script src="<?= asset('js/bootstrap.min.js') ?>"></script>
<!-- AngularJS Application Scripts -->
<script src="<?= asset('app/app.js') ?>"></script>
<script src="<?= asset('app/controllers/employees.js') ?>"></script>
</body>
</html>
sound like your key is being duplicate in ng-repeat. Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: app in apps, Duplicate key: string:<, Duplicate value: <
this issue happens once
Invalid:
ng-repeat="value in [4, 4]"
valid
ng-repeat="value in [4, 4] track by $index"
In your app.js file.
Change the first line to:
var app = angular.module('employees', ['ngRoute'])

Use Modal as a template view and reference to it

I have modal code (below) wrapped in nav.html and it works as expected (login, logout...works).
<div class="modal fade" id="authModal" role="dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<form class="form-signin" role="form">
<input ng-model="user.email" type="email" class="form-control" placeholder="Email address" required="" autofocus="">
<input ng-model="user.password" type="password" class="form-control" placeholder="Password" required="">
<div class="checkbox checkbox-success">
<input ng-model="checkbox.signup" ng-init="checkbox.signup=false" type="checkbox">
<label> Sign Up for first-timer </label>
</div>
<div class="text-center">
<button ng-click="login($event)" class="btn btn-lg btn-primary" type="button">Sign In</button>
</div>
</form>
</div>
</div>
But when I move all modal content to a file named md.html and include it to nav.html via
<div class="navbar-header" ng-controller="MainCtrl">
<div ng-include="'views/modals/md.html'"></div>
</div>
It is absolute that I have it included in the ng-controller div.
On testing, I got error of unable to reference to user.password for the Controller. The controller works fine previously and I didn't change anything on it. For this question, I m posting a simplified version of modal and controller code.
$scope.login = function($event){ $event.preventDefault();
// console.log("cond ", cond, ".checkbox.signup ", $scope.checkbox.signup);
if (!$scope.logged)
fn.login($scope.user, function(){
if ($scope.checkbox.signup) fn.signup($scope.user);
});
};
var fn = {
login: function(user, cb){
if (Auth.authData) return;
if (!user.password) {
fn.alert("please type password");
return;
}
if (fn.valid_email(user.email))
Auth.ref_ds1.authWithPassword(user, function(error, authData) {
if (error) {
fn.alert(error);
cb();
} else {
authData.email = $scope.user.email;
console.log("Authenticated successfully on:", authData.email);
fn.greet("Hello " + authData.email.split("#")[0]);
$scope.logged = true;
window.location.href = "/";
}
});
}
}
How to reference them correctly?
It looks like you could be seeing issues with your ng-include creating another scope and you're not able to reference the previously defined user object.
One way I avoid confusion with scopes is using "Controller as" syntax to reference a scope specifically (see http://www.johnpapa.net/angularjss-controller-as-and-the-vm-variable/). Here's a tiny example:
// in the controller
app.controller('MainController', function() {
var vm = this;
this.somevalue = 'something';
})
// markup
<div ng-controller="MainCtrl as ctrl">
{{ ctrl.somevalue }}
<div ng-controller="SecondCtrl as secondCtrl">
{{ ctrl.somevalue }}
{{ secondCtrl.anothervalue }}
</div>
</div>
Using "Controller as" will really help unwind scope problems you're having, but it would take some re-tooling of your original controller.

Values of certain fields that precede a specific button class onClick are undefined?

Thought to test something like this to get the values of fields that precede a repeating UpdateButton's click, but it logs undefined values in the browser console
var $prevID = $(this).prevAll('.UpdateStory').first(".storyID");
var $prevStory = $(this).prevAll('.UpdateStory').first(".currentStory");
var id = $prevID.val();
var story = $prevStory.val();
Here's the HTML (client-side + server-side handlebars.js)
<div id="allStories" class="allStories"> </div><!--/allStories-->
<script id="storyTemplate" type="text/x-handlebars-template">
<div class="thisness">
<div class="stories">
<div class="new" id="new">
\{{#each stories}}
<div class="container-fluid">
<div class="row">
<div class="col-sm-4 col-sm-offset-4">
<form class="updateNewStoryForm">
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox">
</span>
<input type="hidden" class="storyID" value="\{{ _id }}"/>
<input type="text" class="currentStory" value="\{{ story }}">
<span class="input-group-addon">
<input type="button" class="UpdateStory">
</span>
</div><!-- /input-group -->
</form>
</div><!-- /.col-lg-6 -->
</div><!-- /.row -->
</div><!-- /.container-fluid -->
\{{/each}}
</div>
</div> <!--/stories-->
</div> <!--/thisness-->
</script>
And here's the ajax .put that otherwise only updates the first story
// UpdateStory button clicks
$(".allStories").on('click','.UpdateStory',function(e) {
e.preventDefault();
console.log('UpdateStory clicked');
// story elements for API that work for only the first item,
// regardless of whichever UpdateStory button is clicked
var id = $( ".storyID" ).val();
var story = $( ".currentStory" ).val();
console.log(id);
console.log(story);
var AjaxPostData = {
id : id,
story : story
};
// if the story field has content
if (story.length != 0) {
console.log('there is a story: ' + story);
// make an ajax call
$.ajax({
dataType: 'json',
data: AjaxPostData,
type: 'put',
url:"http://localhost:4200/api/v1/stories/" + id,
success: refreshNewStories,
error: foundAllNewFailure
});
};
}); // UPDATE
It should be:
var group = $(this).closest(".input-group-addon");
var id = group.prevAll(".storyID").val();
var story = group.prevAll(".currentStory").val();

Categories

Resources