Reloading form does not update in AngularJS? - angularjs

I am creating a form, where when the user clicks on the edit button to edit the text, it works fine. But when user clicks on the update button then reload the page it does not show the updated text after reloading the page.
Here is the plunker, that it worked but the code below does not work when page reloads. (I want to do this only with Front-End)
http://plnkr.co/edit/yyDf2SuEvefLWIK13kS4?p=preview
Here is my code.
<div class="people-view">
<h2 class="name">{{people.first}}</h2>
<h2 class="name">{{people.last}}</h2>
<span class="title">{{people.title}}</span>
<span class="date">{{people.date}} </span>
</div>
<div ng-controller="MyCtrl">
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="people.first">
<br>
<b>Last Name:</b>
<input type="text" ng-model="people.last">
<br>
<b>Email:</b>
<input type="email" ng-model="people.email">
<br>
<b>Phone:</b>
<input type="num" ng-model="people.phone">
<br>
<b>Website:</b>
<input type="text" ng-model="people.website">
<br>
<b>Education:</b>
<input type="text" ng-model="people.education">
<br>
<b>Education Year:</b>
<input type="text" ng-model="people.year">
<br>
<legend>Address</legend>
<b>Street:</b>
<input type="text" ng-model="people.street">
<br>
<b>City:</b>
<input type="text" ng-model="people.city">
<br>
<b>State:</b>
<input type="text" ng-model="people.state">
<br>
<b>Zip:</b>
<input type="text" ng-model="people.zip">
<br>
</fieldset>
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="save()">Save</button>
</form>
</div>
</div>
App.js
var app = angular.module("Portal", []);
app.controller('MyCtrl', function($scope) {
$scope.inactive = true;
$scope.save = function() {
$scope.msg = 'Data sent: '+ JSON.stringify($scope.people);
};
});
JSON file
[
{
"id": "0",
"first": "John",
"last": "Smith",
"img": "//placehold.it/100x100",
"title": "Family",
"date": "Joined 4/2/17",
"email": "jsmith#email.com",
"phone": "555-555-5555",
"website": "www.google.com",
"education": "NYU Law",
"year": "2008",
"street": "123 Main Street",
"city": "Los Angeles",
"state": "CA",
"zip": "1234567"
},
]
Controller
app.controller('PeopleController',['$scope', 'people', '$routeParams',
function($scope, people, $routeParams) {
people.success(function(data) {
$scope.people = data[$routeParams.id];
});
}]);

You can try using the prevent default handler:
ng-click="save($event)"
In your controller, you can put:
$scope.save = function (event) {
event.preventDefault();
$scope.msg = 'Data sent: '+ JSON.stringify($scope.people);
}

to make your changes permanent you have to store it to some sort of storage. files is ok but it's not the best choice. So you may consider using local storage. here is good tutorial of how to handle
local-storage. so the controller will be like
app.controller('myCtrl', ['$scope', function($scope){
$scope.people = {
"first": "John",
"last": "Smith"
}
$scope.myObject = JSON.parse(localStorage.getItem('myObject')) || {
first : $scope.people.first,
last : $scope.people.last
};
$scope.updateThingy = function(){
$scope.people.first = $scope.myObject.first;
$scope.people.last = $scope.myObject.last;
localStorage.setItem('myObject', JSON.stringify($scope.myObject));
};
}]);
here is the plunker. Good luck

Related

AngularJS 2-way binding with TaffyDB

I can't seem to get the scope variables display on the html particularly $scope.r. I can only get scope variables through ng-repeat but not individually. The $scope.r is a pure js object retrieved from TaffyDB record object. I also can get values from the ng-model object within the html but not scope variables from the javascript file not being used within the ng-repeat directive. Am I doing anything wrong?
<script src="https://github.com/typicaljoe/taffydb/raw/master/taffy.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<label class="item item-input item-stacked-label">
<span class="input-label">Definition</span>
<input ng-model="def" ng-value="{{r.defn}}" type="text" placeholder="New Definition ">
</label>
<label class="item">
<span>English Translation</span>
</label>
<label class="item item-input">
<textarea placeholder="English Meaning">
{{r.etrans}}{{r.defn}}
{{def.length}}{{def.charAt(0)}}
{{wdc({ch:def.charAt(0)}).first().allch}}{{wdc({ch:def.charAt(0)}).count()}}
</textarea>
</label>
Here's the javascript
var defs = TAFFY([]);
var emptydb=false;
defs.store('wdic');
.controller('ListController', ['$scope', '$http', '$state', '$location',
function($scope, $http, $state,$location) {
$http.get('js/wdc.json').success(function(data) {
$scope.wdc2 = TAFFY(data);
$scope.whichartist=$state.params.aId;
$scope.data = { showDelete: false, showReorder: false };
$scope.defs=defs;
$scope.r =$scope.defs({___id:$state.params.aId}).first();
$scope.defs().each(function (r) {console.log(r.defn+'~'+r.___id)});
console.log("here"+$scope.r.etrans);
$scope.addurl ="#/tab/list/add";
$scope.wdc=TAFFY([
{
"id": 1,
"ch": "a",
"basech": "a",
"allch": "a,ā,á,à"
},
{
"id": 2,
"ch": "à",
"basech": "a",
"allch": "a,ā,á,à"
},
{
"id": 3,
"ch": "ā",
"basech": "a",
"allch": "a,ā,á,à"
},
{
"id": 4,
"ch": "á",
"basech": "a",
"allch": "a,ā,á,à"
}
]);
});
}]);

Display selected option in drop down using angular

I have one form and am getting values for this form ,from loadEditLevDetails function.
I have binded all the field values except leave type field,I don't knwo how to bind it.
One more thing when I click edit button I can able to change the field values and I can choose some other drop down option,for that I am loading data from getLeaveTypeList method.Based on selected option available leaves field will be auto populated.
<body ng-app="intranet_App" ng-controller="myCtrl" ng-init="init()">
<div class="container">
<form id="row editLeaveDetails" ng-repeat="data in leaveDetails">
<div>
<label>Leave Applied On</label>
<input type="text" name="" ng-model="data.From | date : 'dd/MM/yyyy' ">
</div>
<div>
<label>Leave Type</label>
<select type="text" name="" class="col-xs-12 form-control rField" id="levType" ng-model="data.Leave_type_id" ng-blur="leaveBalance(data.Leave_type_id)"><option value="" selected="selected">Select</option><option data-ng-repeat="data in leaveTypes" value="{{data.id}}">{{data.Name}}</option></select>
</div>
<div>
<label>Availabe Leaves</label>
<input type="text" name="" id="levTaken" >
</div>
<div>
<label>Date From</label>
<input type="text" id="levFrom" onfocus="(this.type='date')" ng-model="data.From | date : 'dd/MM/yyyy' ">
</div>
<div>
<label>Date To</label>
<input type="text" id="levTo" onfocus="(this.type='date')" ng-model="data.To | date : 'dd/MM/yyyy'" >
</div>
<div>
<label>Duration</label>
<input type="text" id="levDuration" ng-model="data.Duration">
</div>
<div>
<label>Reason</label>
<textarea id="LevReason" ng-model="data.Note"></textarea>
</div>
<div class="row pull-right ">
<button class="btn btn-warning editLevDetails btnLeft" ng-click="editDetails()" ng-if="!editMode">Edit</button>
</div>
</form>
</div>
</body>
<script>
var app=angular
.module('intranet_App', [])
.controller('myCtrl', function ($scope, $http) {
$scope.editMode = false;
$scope.init = function () {
$scope.loadLeaves();
$http.post("/leave/getLeaveTypeList").then(function (response) {
$scope.leaveTypes = response.data;
})
}
$scope.loadEditLevDetails = function (id) {
$scope.Id = { leaveRequestId: id };
console.log($scope.Id)
var requestHeaders = {
'content-type': 'application/json'
}
var httpRequest = {
method: 'post',
url: "/leave/editLeaveRequest",
headers: requestHeaders,
data: $scope.Id
}
$http(httpRequest).then(function (response) {
$scope.leaveDetails = response.data;
console.log($scope.leaveDetails)
})
}
$scope.leaveBalance = function (selectedvalue) {
$scope.leaveTypeId = { leaveTypeId: selectedvalue };
var requestHeaders = {
"content-type": 'application/json'
}
var httpRequest = {
method: 'POST',
url: '/leave/getLeaveBalenceCount',
headers: requestHeaders,
data: $scope.leaveTypeId
}
$http(httpRequest).then(function (response) {
$scope.noOfValues = response.data;
$scope.balanceCount = $scope.noOfValues[0].balance_count;
})
}
})
</script>
Please let me know anyone,how to display selected option in dropdown? This is my leaveTypes json.
Try use ng-options directive.
<select ng-model="data.Leave_type_id"
ng-options="leaveType.id as leaveType.name for leaveType in leaveTypes">
<option>Select</option>
</select>
There are two ways you can achieve this :
1. You can add a property name as selected in each object and mark one of them is true which you want to pre-populated in the dropdown.
DEMO
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.leaveTypes = [{
id: 1,
Name: 'Casual Leave',
Selected: false
}, {
id: 2,
Name: 'National Leave',
Selected: true
}, {
id: 3,
Name: 'Regional Leave',
Selected: false
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyController">
<label>Leave Type</label>
<select type="text" name="" class="col-xs-12 form-control rField" id="levType">
<option value="0">Select</option>
<option data-ng-repeat="data in leaveTypes" value="{{data.id}}" ng-selected="{{ data.Selected == true }}">{{data.Name}}</option>
</select>
</div>
You can assign a selected value into the ng-model of the select element.
DEMO
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.leaveTypes = [{
"id": "1",
Name: 'Casual Leave'
}, {
"id": "2",
Name: 'National Leave'
}, {
"id": "3",
Name: 'Regional Leave'
}];
$scope.selected = {"id": "2"};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyController">
<label>Leave Type</label>
<select type="text" name="" class="col-xs-12 form-control rField" id="levType" ng-model="selected.id">
<option value="0">Select</option>
<option data-ng-repeat="data in leaveTypes" value="{{data.id}}">{{data.Name}}</option>
</select>
</div>

Using ng-repeat with ng-model modifies wrong object

TLDR: Here's a plnkr of the issue: https://plnkr.co/edit/HfRoCgPfdoZNxmTtDLf7?p=preview
I have a form with checkboxes:
<div class="form-group">
<div class="input-group">
<div class="checkbox">
<label>
<input type="checkbox" ng-model="rental.car2go.airport.berlin"> Berlin
</label>
<br/>
<label>
<input type="checkbox" ng-model="rental.car2go.airport.hamburg"> Hamburg
</label>
<br/>
</div>
</div>
</div>
that is modifying the rental object. This is how the controller looks like:
angular.module('c2gyoApp', []).controller('c2gyoAppController', [
'$scope',
'state',
function($scope, state) {
$scope.airports = [{
"name": "Berlin",
"model": "rental.car2go.airport.berlin"
}, {
"name": "Hamburg",
"model": "rental.car2go.airport.hamburg"
}, ];
$scope.rental = state.rental;
}]).factory('state', function() {
var rental = {
car2go: {
airport: {
berlin: false,
hamburg: false
}
}
};
return {
rental: rental
};
});
Now I want to use ng-repeat:
<div class="form-group">
<div class="input-group">
<div class="checkbox">
<span ng-repeat="airport in airports">
<label>
<input type="checkbox"
ng-model="airport.model">
{{airport.name}}
</label>
<br>
</span>
</div>
</div>
</div>
With ng-repeat the form is modifying the airports object (airports[1].model=true/false and airports[2].model=true/false).
It should only use the string of that airport object(rental.car2go.airport.berlin and rental.car2go.airport.hamburg ) and modify the rental object. I'm looking for a way to pass the string to ng-model, not the airports object. How can I do this?
Edit: removed the directive, new plnkr
The JSON you are changing is:
$scope.airports = [{
"airport": "Berlin",
"model": "rental.car2go.airport.berlin"
}, {
"airport": "Hamburg",
"model": "rental.car2go.airport.hamburg"
}, ];
where `airports[0].model="rental.car2go.airport.berlin", meaning the string rental.car2go.airport.berlin. This string is replaced with TRUE or FALSE. I guess that you were expecting rental.car2go.airport.berlin to be interpreted as a structure, right? Well, it is not a structure but just a string.
Indeed as #Claies suggested I had to copy the value to the rental array. I used a ng-change function for that. New ng-repeat:
<span ng-repeat="airport in airports">
<label>
<input type="checkbox"
ng-model="airport.model"
ng-change="changeAirport(airport)">
{{airport.name}}
</label>
<br>
</span>
In the controller:
$scope.changeAirport = function(airport) {
var airportName = $filter('lowercase')(airport.name);
state.rental.car2go.airport[airportName] = airport.model;
}

adding input values from form to json object using angularjs

am trying to add the value of input field to json object using angularjs i wrote some codes but it doesn't work, please i need help
script section
<script>
var app = angular.module("exampleApp", []);
app.controller("defaultCtrl", function ($scope, $http) {
$scope.loadData = function () {
$http.get("productData.json").then(function (response) {
console.log("Status: " + response.status);
console.log("Type: " + response.headers("content-type"));
console.log("Length: " + response.headers("content-length"));
$scope.products = response.data;
});
$scope.products = {name:'',age:'',isDead:''};
$scope.resurrect = function(item){
item.isDead = false;
};
$scope.addnew = function(){
$scope.products.mname = $scope.products.name;
$scope.products.mage = $scope.products.age;
$scope.products.misDead = $scope.products.isDead;
};
}
});
</script>
productData.json
[
{ "name": "Tommen Baratheon", "age": "23", "isDead": true },
{ "name": "Roose Bolton", "age": "32", "isDead": false },
{ "name": "Theon Greyjoy", "age": "27", "isDead": true},
{ "name": "Cersei Lannister", "age": "31", "isDead": false}
]
form section
<form>
<input type="text" placeholder="Enter Charater name" class="form- control" ng-model="products.mname">
<input type="number" placeholder="Enter Charater age" class="form-control" ng-model="products.mage">
<input type="text" placeholder="Enter True or false" class="form-control" ng-model="products.misDead">
<input type="submit" value="andNew" ng-submit="addnew()"></form>
So the first problem is that $scope.products is an array. Your markup is bound as if it's a single object though.
<form>
<div ng-repeat="p in products">
<input type="text" placeholder="Enter Charater name" class="form-control" ng-model="p.name">
<input type="number" placeholder="Enter Charater age" class="form-control" ng-model="p.age">
<input type="text" placeholder="Enter True or false" class="form-control" ng-model="p.isDead">
<input type="submit" value="andNew" ng-submit="addnew()">
</div>
</form>
The other problem was that you had bindings like products.mname, but the field is actually name. The next problem you have is you're initializing products as an object when you really should just initialize it as an empty array:
$scope.products = [];
The next problem you'll have is addnew. It needs to just push a new object on to the array:
$scope.addnew = function() {
$scope.products.push({});
};
That will cause a new div to be rendered inside the form.

AngularJS dynamic Form does not get valid

I have a dynamic Form in AngularJS, the input tags get replaced according to question type selected by the user. So the problem is, when user left a input tag blank which is required and switched to another type of questions, the form remains invalid(even the current form is valid).
I am adding the JsFiddle for it, you will get the idea.
HTML
<body ng-app="myApp" ng-controller="myCtrl">
<form name="myForm" novalidate>
<div><input name='name' type='text' ng-model='name' ng-required='true' placeholder='name'></div>
<div compile="myHtml"></div>
<input type="radio" ng-required='true' ng-click="addQuestion(1)" ng-model="radio" value="1"> Question 1 & 3
<input type="radio" ng-required='true' ng-click="addQuestion(2)" ng-model="radio" value="2"> Question 2 & 4
<input type="submit" name="submit" ng-click="" ng-disabled="myForm.$invalid">
</form>
</body>
Javascript
// the main (app) module
var myApp = angular.module("myApp", []);
// add a controller
myApp.controller("myCtrl", function($scope) {
$scope.name = "John Doe";
$scope.myHtml = "";
$scope.radio="1";
$scope.question1 = 1;
$scope.question2 = 2;
$scope.question4 = 4;
$scope.addQuestion = function(id) {
$scope.myHtml = "";
if(id == 1) {
$scope.myHtml += "<div><input name='question1' type='text' ng-model='question1' ng-required='true' placeholder='Question 1'></div>";
$scope.myHtml += "<div><input name='question3' type='text' ng-model='question3' ng-required='true' placeholder='Question 3'></div>";
};
if(id == 2) {
$scope.myHtml += "<div><input name='question2' type='text' ng-model='question2' ng-required='true' placeholder='Question 2'></div>";
$scope.myHtml += "<div><input name='question4' type='text' ng-model='question4' ng-required='true' placeholder='Question 4'></div>";
};
};
$scope.addQuestion(1);
});
// add a directive
myApp.directive('compile', ['$compile', function ($compile) {
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
}]);
Server JSON for question
$scope.fields = [{
"caption": "Gender",
"questionType": "RADIO",
"optionValues": ["Male", "Female"],
"fieldPriority": "REQUIRED"
}, {
"caption": "City",
"questionType": "TEXT",
"optionValues": "",
"fieldPriority": "REQUIRED"
}, {
"caption": "Address",
"questionType": "PARAGRAPH_TEXT",
"optionValues": "",
"fieldPriority": "REQUIRED"
}, {
"caption": "Nationality",
"questionType": "LIST",
"optionValues": ["Indian", "American"],
"fieldPriority": "REQUIRED"
}, {
"caption": "Tea/Coffee",
"questionType": "CHECKBOX",
"optionValues": ["Tea", "Coffee"],
"fieldPriority": "REQUIRED"
}];
Thanks
Do not store plane html in controller. Just use ng-if or ng-show to handle your logic.
I'd refactor your code to use ng-include instead of compiling html from controller which is completely bad pattern in angularjs.
You could inject the template on basis of radio value ng-model
<body ng-app="myApp" ng-controller="myCtrl">
<form name="myForm" novalidate>
<div>
<input name='name' type='text' ng-model='name' ng-required='true' placeholder='name'/>
</div>
<div ng-include="'question-set-'+radio +'.html'"></div>
<input type="radio" ng-required='true' ng-click="addQuestion(1)" ng-model="radio" value="1" />Question 1 & 3
<input type="radio" ng-required='true' ng-click="addQuestion(2)" ng-model="radio" value="2" />Question 2 & 4
<input type="submit" name="submit" ng-click="" ng-disabled="myForm.$invalid">
</form>
</body>
<script type="text/ng-template" id="question-set-1.html">
<div> <input name = 'question1' type='text' ng-model = 'question1' ng-required = 'true' placeholder = 'Question 1' /> </div>
<div><input name='question3' type='text' ng-model='question3' ng-required='true' placeholder='Question 3'/> </div>
</script>
<script type="text/ng-template" id="question-set-2.html">
<div><input name ='question2' type ='text' ng-model='question2' ng-required = 'true' placeholder = 'Question 2' /> </div>
<div><input name='question4' type='text' ng-model='question4' ng-required='true' placeholder='Question 4'/> </div>
</script>
Working Fiddle

Resources