im having ng-change function in the name of myFunc() to store the response from html listitem.
the respose value is getting saved in the local variable of the function but when i refresh the controller or page the values are deleted. i need to store the value during ng-change in myFunc() after multiple page or controller refersh the value will be stored in the controller variable to do the further logics
on page onload
myhtml code
<div class="col-sm-4">
<ol name="ManualFiles" title="Select" required validType="select" ng-
change="myFunc()" ng-model="data.manualsFiles" ng-selected="
{{data.manualsFiles}}">
<li nya-bs-option="type in manualsFiles" data-value="type.key">
<a> {{type.val}} </a>
</li>
</ol>
</div>
mycontroller code
$scope.myFunc = function() {
var manualFile=$scope.data.manualsFiles;
var cdSoftwares=$scope.data.cdSoftware;
var price=$scope.data.priceBook;
var referenceBooks=$scope.data.referenceBook;
var vpnAccounts=$scope.data.vpnAccount;
if((manualFile && cdSoftwares && price && referenceBooks && vpnAccounts)!==0)
{
$scope.isTypeDisabled=false;
}
else
{
$scope.isTypeDisabled=true;
$scope.data.status="Pending";
}
};
Try it using sessionStorage. In that way, you would not lose your values at least the user closes the window.
Now, the idea is, in the function myFunc,
$scope.myFunc = function() {
var manualFile=$scope.data.manualsFiles;
var cdSoftwares=$scope.data.cdSoftware;
var price=$scope.data.priceBook;
var referenceBooks=$scope.data.referenceBook;
var vpnAccounts=$scope.data.vpnAccount;
//Here, use sessionStorage to save your values in the browser.
var data = {'manualFile': manualFile, 'cdSoftwares': cdSoftwares, 'price': price, 'referenceBooks': referenceBooks, 'vpnAccounts': vpnAccounts}
sessionStorage.setItem('yourNameKey', data);
if((manualFile && cdSoftwares && price && referenceBooks && vpnAccounts)!==0)
{
$scope.isTypeDisabled=false;
}
else
{
$scope.isTypeDisabled=true;
$scope.data.status="Pending";
}
};
Then, when Users are refreshing the site, you would create a function just for recover that values in your variables. You'd use destructuring assignment to recover your values.
function recoverValues() {
var data = sessionStorage.getItem('yourNameKey');
var { manualFile, cdSoftwares, price, referenceBooks, vpnAccounts } = data;
}
recoverValues();
You can use sessionStorage property of $window.
Note: The data stored using sessionStorage will be available only in that session. (data will get deleted when the browser tab is closed)
You can achieve your requirement using this example. Try this demo
<script type="text/javascript">
var app = angular.module('MyApp', ["ngStorage"])
app.controller('MyController', function ($scope, $localStorage, $sessionStorage, $window) {
$scope.Save = function () {
$localStorage.LocalMessage = "LocalStorage: My name is Pet Jones.";
$sessionStorage.SessionMessage = "SessionStorage: My name isPet Jones.";
OR
$sessionStorage.setItem("status", "pending");
}
$scope.Get = function () {
$window.alert($localStorage.LocalMessage + "\n" + $sessionStorage.SessionMessage);
OR
console.log($sessionStorage.getItem("status"))
}
});
</script>
Related
I have a tag like this :
<a data-ng-click="showform(#item.CategoryId)">
I have a variable "catid" in razor...
#{int catid; }
I want save value in 'catid'
this my js code :
app.controller('Result', function ($scope) {
$scope.CatId = 0;
$scope.showform = function (id) {
$scope.CatId = id;
}
});
i want to use CatId for a linq code and show category name at view
Can you give me a sample code?
Following is a working example, you can refer to it.
<div ng-app="myApp" ng-controller="Result">
#foreach (var item in Model)
{
<a data-ng-click="showform(#item.CategoryId)">CategoryId is #item.CategoryId</a>
<br />
}
<h2>Name of selected Category is {{CatName}}</h2>
</div>
Make request(s) using AngularJS $http service
<script>
var app = angular.module('myApp', []);
app.controller('Result', function ($scope, $http) {
$scope.CatId = 0;
$scope.CatName = "";
$scope.showform = function (id) {
$scope.CatId = id;
$http.get("/GetCategoryNameById?catid=" + id)
.then(function (response) {
$scope.CatName = response.data;
//your code logic here based on your actual requirement
});
}
});
</script>
My GetCategoryNameById action method for testing purpose
[HttpGet("GetCategoryNameById")]
public IActionResult GetCategoryNameById(int catid)
{
//your code logic here
//query data based on received catid
var category = _dbcontext.Categories.Where(c => c.CategoryId == catid).FirstOrDefault();
return Ok($"{category.CategoryName}");
}
Test Result
Maybe you can use this way.
<input type="hidden" name="catid" id="catid" value="{{Catid}}" />
When you submit form this value passed to asp.net core.
I'm at my wits end! In angular I've got a controller and a view.
There are 2 dropdowns on the page which need to reset to default once the restart button has been clicked.
I can set the value of the boxes as they render by pushing a "select" option into the collection inside the controller. However, when the reset button is pressed, which runs the init() method again, the dropdowns should be set back to the first value. This doesn't occur, the values for $scope.selectedYear and $scope.selectedReport remain as they did before the reset button was pressed.
This is the full code for the controller
function TreeReportsCHLController($scope, $q, $routeParams, reportsDashboardResource, navigationService, notificationsService, dialogService, entriesManageDashboardResource, $timeout) {
// Methods
var generalError = function () {
notificationsService.error("Ooops", "There was an error fetching the data");
$scope.actionInProgress = false;
}
// Scope
$scope.selectedYear = "";
$scope.init = function () {
$scope.hasCompleted = false;
$scope.actionInProgress = false;
$scope.yearSelected = false;
$scope.reportTypes = ["Choose", "Entered", "ShortListed", "Winner", "Recieved"];
$scope.selectedReport = "";
$scope.entryYears = new Array();
$scope.entryYears.push("Choose a Year");
entriesManageDashboardResource.getEntryYears().then(function (response) {
angular.forEach(response, function (value, key) {
$scope.entryYears.push(value);
});
});
$scope.selectedYear = $scope.entryYears[0];
$scope.selectedReport = $scope.reportTypes[0];
};
$scope.yearHasSelected = function(selectedYear) {
$scope.yearSelected = true;
$scope.selectedYear = selectedYear;
};
$scope.generateFile = function (selectedReport) {
$scope.actionInProgress = true;
var reportDetail = {
entryYear: $scope.selectedYear,
chosenEntryStatus: selectedReport
};
reportsDashboardResource.generateEntriesReportDownloadLink(reportDetail).then(function (response) {
if (response.Successful) {
$scope.hasCompleted = true;
} else {
notificationsService.error("Ooops", response.ErrorMessage);
}
$scope.actionInProgress = false;
}, generalError);
};
$scope.restart = function () {
$scope.init();
}
// Initialise Page
$scope.init();
}
angular.module("umbraco").controller("ReportsDashboardController", TreeReportsCHLController)
this is the code with the dropdowns in it;
<table>
<tr>
<td>Get a report for year: {{selectedYear}}</td>
<td><select ng-model="selectedYear" ng-change="yearHasSelected(selectedYear)" ng-options="year for year in entryYears" no-dirty-check></select></td>
</tr>
<tr ng-show="!hasCompleted && yearSelected">
<td>
Get Report Type:
</td>
<td>
<select ng-model="selectedReport" ng-change="generateFile(selectedReport)" ng-options="status for status in reportTypes" no-dirty-check ng-disabled="actionInProgress"></select>
</td>
</tr>
</table>
I've also done a further test where I simply set $scope.selectedYear to $scope.entryYears[0] within the reset method. When I console.log $scope.selectedYear here, the value confirms it has been changed, but strangely where I've outputted the $scope.selectedYear / {{selectedYear}} to the page for testing, this does not update. It's almost as though the binding between the controller and the view isn't occuring.
Any help?
Thank-you.
Here's a working plunk that is somewhat stripped down since I didn't have access to of the services that your are injecting into your controller. The changes I made in the controller are:
First,
$scope.entryYears = new Array();
becomes
$scope.entryYears = [];
as this is the preferred way to declare an array in js.
Second, I removed $scope.apply() that was wrapping
$scope.selectedYear = $scope.entryYears[0];
$scope.selectedReport = $scope.reportTypes[0];
as this was causing infinite digest cycles.
I have a simple form with a checkbox which clicked deletes a property from an object.
Here is the controller:
app.controller('PropController', function ($scope) {
var str = '{"meta":{"aprop":"lprop"},"props":{"gprop":12,"lprop":9,"wrop":5}}';
$scope.filecontent = JSON.parse(str);
$scope.delprop = false;
$scope.propobj = $scope.filecontent.props;
$scope.proptodel = $scope.filecontent.meta.prop;
var mainvalue = $scope.propobj[$scope.proptodel];
$scope.$watch('delprop', function () {
if ($scope.delprop == true) {
delete $scope.propobj[$scope.proptodel];
} else {
$scope.propobj[$scope.proptodel] = mainvalue;
}
});
And the view:
<div ng-app="SomeProperties" ng-controller="PropController">
<div ng-if="proptodel">
there is a property to delete: {{proptodel}}
<form><input type="checkbox" ng-model="delprop"></form>
filecontent: {{filecontent}}
</div>
<div ng-if="!proptodel">
there is NO property to delete
</div>
</div>
The app on jsfiddle.
The problem appears when the form is in the ng-if, it stops behaving. As you can try it in the jsfiddle, when I delete ng-if="proptodel" from the div containing the form, it working normally. What is the explanation of this?
You need to put the delprop into in object to make ng-model work properly. That means your markup should have:
<form><input type="checkbox" ng-model="obj.delprop"></form>
And your Javascript code should look like:
$scope.obj = {
delprop: false
};
$scope.propobj = $scope.filecontent.props;
$scope.proptodel = $scope.filecontent.meta.prop;
var mainvalue = $scope.propobj[$scope.proptodel];
$scope.$watch('obj.delprop', function () {
if ($scope.obj.delprop == true) {
delete $scope.propobj[$scope.proptodel];
} else {
$scope.propobj[$scope.proptodel] = mainvalue;
}
});
Of course you should find a proper name for the object as obj is really bad and generic ;-)
I have a form with two input fields (session.email and session.psw) bound to the LoginController.session attribute. When I click the reset button, I call the LoginController.reset() function.
I would like make it clear the session attribute, utilizing the variable sessionDefault (empty). However it works just one time, if I reset two times the form, sessionDefault is undefined.
How could I make it as a constant attribute of the controller?
app.controller('LoginController', function ($scope)
{
this.session={};
var sessionDefault=
{
email : "",
psw: ""
};
this.reset = function()
{ this.session = sessionDefault; };
});
Try out this out
for reset function just reset it with sessionDefault copy like as shown below
vm.reset = function () {
vm.session = angular.copy(sessionDefault);
};
here this refers to the controller instance
Notice that I use var vm = this; and then I decorate vm with the members that should be exposed and data-bindable to to the View. vm simply denotes view modal
This does 3 things for me.
Provides a consistent and readable method of creating bindings in my controllers
Removes any issues of dealing with this scoping or binding (i.e. closures in nested functions)
Removes $scope from the controller unless I explicitly need it for something else
Working Demo
script
var app = angular.module('myApp', []);
app.controller('LoginController', function ($scope) {
var vm = this;
vm.session = {};
var sessionDefault = {
email: "",
psw: ""
};
vm.reset = function () {
vm.session = angular.copy(sessionDefault);
};
});
html
<div ng-app='myApp' ng-controller="LoginController as login">
Email:<input type="text" ng-model="login.session.email"/>{{login.session.email}}
<br>
Psw:<input type="text" ng-model="login.session.psw"/>{{login.session.psw}}
<br>
<button ng-click="login.reset()">Reset</button>
</div>
Take a look at this beautiful stuff.
AngularJS’s Controller As and the vm Variable
this.reset = function()
{ this.session = sessionDefault; };
The this in this context refers to the function (reset). If you want to access the 'original' this you need to store it in a variable.
app.controller('LoginController', function ($scope)
{
this.session={};
var sessionDefault=
{
email : "",
psw: ""
};
var self = this;
this.reset = function()
{ self.session = angular.clone( sessionDefault); };
});
I've a list on ng-repeat that displays a list of results from a $http query (bind to an input). I'd like both for the list to disappear when the user clicks on one of the results and for the initial empty value of the model to be restored.
Basically, the functionality is as follows:
User searches term, list displays results, user clicks on result, list disappears, user clicks on input again to make another search, list with new results appear.
So far I've managed to make the list disappear, but not to make it appear again when the user makes another search.
Here's the relevant code:
<input type="text" ng-model="name" ng-click="Research()"/>
<ul ng-hide="clicked" ng-show="retype">
<li ng-repeat="result in results" ng-click="getDetails(result.id)">{{result.title}}</li>
</ul>
And the JS:
function Ctrl($scope, $http) {
var get_results = function(name) {
if (name) {
$http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=8').
success(function(data3) {
$scope.results = data3.results;
});
}
}
$scope.name = '';
$scope.$watch('name', get_results, true);
$scope.getDetails = function (id) {
$http.get('http://api.discogs.com/artists/' + id).
success(function(data) {
$scope.artist = data;
});
$http.get('http://api.discogs.com/artists/' + id + '/releases?page=1&per_page=500').
success(function(data2) {
$scope.releases = data2.releases;
});
$scope.clicked = true;
}
function Research(){
$scope.retype = true,
$scope.name = '';
}
Plunkr is down, I'll make one as soon as possible. Any idea about what am I missing?
I tidied up your code a little bit. Please note that the div is shown only when artist is defined. So when it is set to undefined by the $scope.clear() method, the mentioned div is hidden.
Html part:
<div ng-controller="Ctrl">
<input type="text" ng-model="name" ng-focus="clear()"/>
<ul>
<li ng-repeat="result in results" ng-click="getDetails(result.id)">{{result.title}}</li>
</ul>
<div ng-show="artist">
<h1>Artist</h1>
<ul>
<li>{{artist.name}}</li>
<li>{{artist.release_url}}</li>
<li>{{artist.uri}}</li>
<li>{{artist.resource_url}}</li>
</ul>
</div>
</div>
JavaScript part:
var myApp = angular.module('myApp',[]);
function Ctrl($scope, $http) {
$scope.name = undefined;
$scope.artist = undefined;
$scope.results = undefined;
var search = function (name) {
if (name) {
$http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=8').
success(function(data3) {
$scope.results = data3.results;
});
}
}
$scope.$watch('name', search, true);
$scope.getDetails = function (id) {
$http.get('http://api.discogs.com/artists/' + id).
success(function(data) {
$scope.artist = data;
});
$http.get('http://api.discogs.com/artists/' + id + '/releases?page=1&per_page=500').
success(function(data2) {
$scope.releases = data2.releases;
});
}
$scope.clear = function () {
$scope.name = undefined;
$scope.artist = undefined;
$scope.results = undefined;
}
}
There is working JSFiddle.
Your Research function is unnecessary because you don't need ng-show and ng-hide same time...
secondly you set clicked to ok but never set it false again after your research done...
here is working PLUNKER
Try using just one ng-hide or ng-show, instead of both. Since you never set clicked back to false, it is probably overriding the retype.
Both functions are two-way, so you can just use ng-hide="clicked", and inside function Research, set $scope.clicked to false.