getting values from sessionStorage - javascript

I am trying to get the value from sessionStorage and map it to my ng-model, but
when i do that in my ng-init its not working.
The problem is in my actual code i am inside a ng-repeat so my sessionStorage becomes like below:
sessionStorage.getItem(item.itemId)
HTMl Code:
<div ng-app="">
<div ng-controller="MyCtrl">
Not Working <input ng-init = 'name = sessionStorage.getItem("SavedString")' type="text" ng-model="name" >
Working <input type="text" ng-model="name1" >
</div>
</div>
Controller:
function MyCtrl($scope) {
sessionStorage.setItem("SavedString","I'm a value saved with SessionStorage");
//RETRIEVE VALUE
$scope.name = "test"
$scope.name1 = sessionStorage.getItem("SavedString");
$scope.hi = 'Hello World';
}
Fiddle:
http://jsfiddle.net/393revrn/

i too tried in your way but i didn't find a the requirements to achieve this ......so i tried with making a function call with in init and appended session data to that model then i can see the proper output by making ng-init ='some()' here is the working plunker
UPDATE
From some source i found that HTML cannot understand session variables directly.

The sessionStorage, when accessed from the ng-init directive, is not understood by Angular; it will be parsed and interpreted as if it were a $scope function (which, I assume, is not).
So, in order for your example to work, you should do something like this in your controller:
$scope.sessionStorage = sessionStorage;

Related

AngularJS passing data to Javascript variables and opposite

I am looking for a solution on passing data from a specific input text field to AngularJS. it may be a Javascript variable too. If the variable is changed from inside a javascript code it is not updating on AngularJS side. If i take the same variable and in the text field add at least one character or modify something i see variable updating and everything working as it should.
I tried something with angular.element(document.getElementById('ControllerElementID')).scope().funct(); but still no luck. When i update at least one field from the keyboard, all text fields that are related to "ng-model="sig.sigBase6422"" are updating properly as it should. If i call this updates through a JavaScript function i see updates only on specific text field and no updates at all on ng-model happening. How to make it updating as simple as possible? Below i will post a small example. I was able to store data from variable to a external file and in AngularJS read it from file and use it. this is way too long, complicated and ridiculous. I am sure there should be a better way.
Thank you!
<script type="text/javascript">
function addtext1() {document.getElementById("myID1").value = "1111111111111111";}
function addtext2() {document.getElementById("myID2").value = "2222222222222222";}
</script>
<div>
<form action="#" name="FORM1">
<TEXTAREA NAME="sigData" ng-model="sig.sigBase6422" ROWS="10" COLS="20">String: </TEXTAREA>
</form><br>
<input type="text" name="myID1" id="myID1" ng-model="sig.sigBase6422" ><br>
<input type="text" name="myID2" id="myID2" ng-model="sig.sigBase6422" ><br>
<p>Value {{sig.sigBase6422}}!</p>
</div>
<!-- test field -->
Add text 1
Add text 2
Indeed if you want to use AngularJS for what it was created, you have to rewrite your code completely using directive or controller. You variables and functions accessible from the view should be attached to the $scope too.
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope){
$scope.addtext1 = function () {
$scope.sig.sigBase6422 += "1111111111111111";
};
$scope.addtext2 = function () {
$scope.sig.sigBase6422 += "2222222222222222";
};
$scope.sig = {
sigBase6422: ""
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<form action="#" name="FORM1">
<TEXTAREA ng-model="sig.sigBase6422" ROWS="10" COLS="20">String: </TEXTAREA>
</form><br/>
<input type="text" name="myID1" id="myID1" ng-model="sig.sigBase6422" /><br/>
<input type="text" name="myID2" id="myID2" ng-model="sig.sigBase6422" /><br/>
<p>Value {{sig.sigBase6422}}!</p>
<!-- test field -->
<button ng-click="addtext1()">Add text 1</button>
<button ng-click="addtext2()">Add text 2</button>
</div>
You seem to have misunderstood how angular works. What you're trying to do is not how angular works. What you're trying to do with native JavaScript can be done with angular. Angular can update dom and Dom updates angular as it's responsible for causing updates.... anyway without getting any deeper. You need to read more on how angular works and try sticl within the bounds of angular instead of mixing.
That being said :
Tigger change on the Dom element after you have updated its value. Or better yet get access to scope variable on the Dom and call a function in angular with the value you're and set they value from inside of a angular.
Use this code while updating the value.
pick the controller first using
var scope = angular.element(document.getElementById('yourControllerElementID')).scope();
scope.<variablename> = <your operation>;
then
scope.$apply();
the remaining thing will be taken care by Angular.

Getting the value inside a textbox ng-model using javascript .value

I'm currently confuse in trying to obtain the value inside a text box using jquery .value
<input class="input referral-code" disabled="true" ng-model="account.referral_code_string" id="input-refcode">
I tried using document.getElementById('input-refcode').value to try to obtain the value but it comes out as empty on my console.
But if I tried binding it onto a on-click event, it manages to obtain the value stored inside the ng-model
$('.trigger').on('click', function(){
console.log(document.getElementbyId('input-refcode'))
});
As you can see there is a value inside the text box itself. But when you tried inspecting it, this is what came out.
<input class="input referral-code" disabled="true" ng-model="account.referral_code_string" id="input-refcode">
If you look at there is no value inside the input textbox. I'm not sure if it has something to do with angular.js
You can get the scope object using element
var scope = angular.element(document.getElementById('input-refcode')).scope();
var desiredValue = scope.account.referral_code_string;
This might help you.
inject $timeout service in controller
$timeout(function(){
console.log(document.getElementById('input-refcode')); },200);
Note: Use capital B in getElementById not getElementbyId.
var app = angular.module('todoApp', []);
app.controller('TodoListController', function($scope){
$scope.$watch('referral_code_string'), function(){ console.log($scope.referral_code_string)};
console.log(document.getElementById('input-refcode').value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="todoApp" ng-controller="TodoListController as todoList">
<input class="input referral-code" disabled="true" ng-model="referral_code_string" ng-init="referral_code_string = 'abc'" id="input-refcode" value="abc">
</div>

HTML input has both {{}} and ng-model

I have a form which contains two input fields, I want to sync the next input field when user is typing in the first input field by default, and user can edit the second field as they like, below code works fine:
<input type="text" ng-model="name">
<input type='text' value='{{name}}'>
<button ng-click='submit()'>submit</button>
However, to be able to get the value of second field, I need to put ng-model to the second field, and once I put ng-model, it won't sync anymore.
This is the example
How should I get the second field's value if I don't put a ng-model to it.
Thank you.
You can use ng-change. When user changes input 1 the ng-change method will be called and input2 will be updated .but when user change input 2 nothing will be called .
<DIV ng-app='app'>
<form ng-controller='myController'>
<input type='text' ng-model='name' ng-change="callMe()"/>
<input type='text' ng-model="name2" />{{name2}}
</form>
</DIV>
and controller js
var app = angular.module('app', []);
app.controller('myController', function($scope){
$scope.callMe =function(){
$scope.name2=$scope.name;
}
//$scope.name
//$scope.name2
})
update fiddle example
You could use the $scope.$watch Method for your needings.
I have updatet your fiddle.
What i did is easy, everytime the model changes, the $watch will be called with the new value of the model, then you just need to copy the value into the second model.
First approach that came to my mind was to ng-bind a property with a setter that would do what you want:
<input type='text' ng-model='nameModel' />
then
app.controller('myController', function($scope) {
Object.defineProperty($scope, 'nameModel', {
get: function() { return $scope.name1; },
set: function(x) { $scope.name1 = $scope.name2 = x; }
});
});
This causes any edit to nameModel to affect both name1 and name2.
Fiddle
You could do a similar wrapper around name2 to track whether it has ever been modified (dirty/pristine), and have nameModel only change scope.name2 if it is pristine.
Fiddle with better user experience
(If you're using Angular forms, it tracks the field status for you, so you could directly look at form.name2.$pristine.)
It seems that what you need is to set the value to the scope variable.
So your code would then look like this:
<input type="text" ng-model="name">
<input type='text' value="{{name}}" ng-model="somethingelse">
<button ng-click='submit()'>submit</button>
Hope that helps.

AngularJS changing controller parameter

I have been ploughing into AngularJS and am trying to get my head around how everything links together but I've become a bit stuck.
How can I pass a variable to change the JSON that is loaded and shown on the page?
I thought it would be a button click and the directive would talk to the controller, but how I'm not so sure.
If i have my JSON as something like this as in controller...
var id = 'peter';
var person = $resource('http://myjson.com/'+id+'.json')
I can't figure out how I would change the id based on button clicks for example.
Any help is greatly appreciated
I'll try to explain as simple as possible, you can pass data as argument to a function from HTML to controller using the ngClick directive.
The function inside the controller will be invoked because it has a binding to the ngClick directive using the $scope.
Example:
html:
<div ng-app="App" ng-controller="ctrl">
<div ng-repeat="itemId in items">
<button ng-click="myClickFunc(itemId)">click {{itemId}}</button>
</div>
</div>
js:
var app=angular.module('App', ['ngResource']);
function ctrl($scope,$resource){
$scope.items=[1,2,3,4];
$scope.myClickFunc=function(itemId){
var person = $resource('http://myjson.com/get/:id');
person.get({id: itemId}).$promise.then(function(data) {
// success
$scope.myData = data;
}, function(errResponse) {
// fail
});
}
Live example: http://jsfiddle.net/choroshin/zJ5G6/

AngularJS Stop Replacement of Default Input Value

In AngularJS I have input that is populated by php like so:
<form method="post" ng-controller="PostCtrl">
<input type="text" name="post_title" ng-model="post_title" />
</form>
Now in my Controller, I never to specify ng-model, so I lets imagine I have empty controller:
EngagementApp.controller('PostCtrl', ['$scope',
function($scope) {
return function($scope) {
}
}]);
The problem I am having is that anything tied to an ng-model automaticcaly gets replaced with an empty value. My question is how can I stop the default php value from being replaced if no value in the controller is set?
You can use ng-init to set an inital value. For example
<input type="text" name="post_title"
ng-model="post_title" ng-init="post_title='<?$=phpValue;?>'" />
The HTML value attribute is ignored by AngularJS.
You should could the default values from your controller:
$scope.post_title = 'default value';
But initializing the model from the html by using ng-init ( like #Thomas suggested ) makes more sense in this particular case.

Categories

Resources