How to pass parameter with $location directive in Anjularjs - html

I am new to Anjularjs. I tried to pass parameter with $location directive in Angularjs but console says "category not defined". What i am missing. Here is my code:
$scope.editCategory = function(category) {
alert(category.identity);
$scope.resetError();
$scope.category = category;
$scope.catlist=category;
$location.path('categories/edit').search({param:category});
};
I need to pass that category object in categories/edit url.
It is not working. Thanks in advance.

try this.
$location.path('/myURL/').search({param: 'value'});
will result in
`/myURL/?param=value`
OR
$location.path('/myURL/'+ param1);
Please find $location for more details
EDIT CODE 2:
here what I have tried.
HTML :
<div ng-controller="testCtrl">
<a ng-click="setParam()" href="javascript:void(0)">send query param</a> <br>
<a ng-click="getParam()" href="javascript:void(0)">get query param</a>
</div>
JS :
app.controller("testCtrl",function($scope,$location){
var obj = {
id: "331e25d6-fbb5-42a5-b76d-fcac9b30a26e",
trash: false,
identity: "momo",
description: null,
menuItems : [0,12]
}
$scope.setParam = function(){
$location.search({param: obj})
}
$scope.getParam = function(){
console.log($location.search().param);
}
})
otherway :
$scope.getParam = function(){
var arrParam = $location.search().param;
console.log($location.search().param,arrParam);
}

Related

Scope value not updating in view in IONIC 1 and Angular js

I have a requirement like saving two previous login details.
I am done with it. But my view will update only on refresh.But scope values are updated.
Tried with scope.apply,digest,timeout. But nothing seems to work here.
$scope.loginUserName=localStorage.getItem("loginUserName");
$scope.userName=localStorage.getItem("userName");
$scope.mobileNumber=localStorage.getItem("mobileNumber");
$scope.loginData = {};
$scope.userLogin = function(loginData) {
userService.userLogin(loginData).then(function(success) {
var res=success.message;
if(res==='success'){
if(localStorage.getItem("userName1")==null || localStorage.getItem("userName1") == success.firstName){
localStorage.setItem("userName1",success.firstName);
localStorage.setItem("loginUserName",success.firstName);
}else if(localStorage.getItem("userName2")==null || localStorage.getItem("userName2") == success.firstName ){
localStorage.setItem("userName2",success.firstName);
localStorage.setItem("loginUserName",success.firstName);
}
localStorage.setItem("userName",success.firstName);
$scope.userName=success.firstName;
$scope.mobileNumber = success.mobileNumber;
$scope.loginData = {};
$state.go('app.home');
}else{
$scope.message ='Wrong pin.Try again or click Forgot password to reset it.';
}
},function(error){
});
};
$scope.loginPerson = function(mobileNumber,userName){
localStorage.setItem("loginUserName",userName);
// here userName is updating,but not reflecting in view
$scope.loginUserName=localStorage.getItem("loginUserName");
//setTimeout(function(){ $scope.$apply(); });
console.log("In loginPerson:"+userName);
$state.go('app.start');
}
start.html
<span ng-if="loginUserName !=null">
<p class="startP">Enter pin for {{loginUserName}}
<i class="icon ion-chevron-down" ui-sref="app.loginOptions">
</i></p>
</span>
State
//Here is the state details,I have same controller for two state.
.state('app.loginOptions', {
url: '/loginOptions',
views: {
'menuContent': {
templateUrl: 'templates/loginOptions.html',
controller:'LoginCtrl'
}
}
})
.state('app.start',{
url:'/start',
views:{
'menuContent':{
templateUrl:'templates/start.html',
controller:'LoginCtrl'
}
}
EDIT
I have used within object also,But nothing is changed.
step 1) please use angular copy while get data from localstorage to $scope $scope.xyz=angular.copy(localstorage.get('key'))
after implement step 1 then not work use $scope.$apply(); after set value in $scope.
try to use loginUserName as a property of an object instead a property of scope directly. Sometimes angularjs fail to update view for these values.
Like
$scope.data={
loginUserName:""
};
Then inside your function
$scope.userLogin = function(loginData) {
...
$scope.data.loginUserName=localStorage.getItem("loginUserNa‌​me");
// To check it
console.log($scope.data);
}
html
<span ng-if="data.loginUserName !=null">
...
</span>
Update
Change the loginPerson function like below.
$scope.loginPerson = function(mobileNumber,userName){
localStorage.setItem("loginUserName",userName);
$scope.data.loginUserName=localStorage.getItem("loginUserName");
console.log("In loginPerson:"+userName);
console.log($scope.data);
}

Passing drop down list option to controller

I have a drop down list in the form of the select tag as shown below:
<select id = "1">
<option>Amy</option>
<option>Gi-Anne</option>
</select>
I want to pass the selected option - either Amy or Gi Anne to this method of the controller.
public String name (string nameSelected)
{
var query = new NameQuery();
if(nameSelected.Equals('Amy'))
{run a specific query}
else if(nameSelected.Equals('Gi-Anne'))
{run a specific query}
}
How do I pass the parameter of the selected drop down list value to the controller? Appreciate your help and thanks in advance.
This is 'fairly' easy using AngularJS, see this Plunk for a (simulated) example.
The HTML changes to this:
<body ng-app="myApp">
<div ng-controller="myController">
State: {{onChangeText}}
<br/>
<select ng-model="selectedItemId" id="itemList" ng-change="onChange()">
<option value="{{item.id}}" ng-selected="{{item.id == selectedItemId}}" ng-repeat="item in items">{{item.name}}</option>
</select>
<br/>
{{selectedQuery}}
</div>
</body>
With a controller like this:
app.controller("myController", [
"$scope",
"$http",
function($scope, $http){
var self = {};
self.simulatedGetQuery = function() {
console.log($scope.selectedItemId);
$scope.selectedQuery = "";
switch($scope.selectedItemId) {
case "1":
$scope.selectedQuery = "Query Amy";
break;
case "2":
$scope.selectedQuery = "Query Gi-Anne";
break;
}
};
self.httpGetQuery = function() {
$http({
method: 'GET',
url: 'http://somehostname/action/' + $scope.selectedItemId
}).then(function successCallback(response) {
$scope.selectedQuery = response;
}, function errorCallback(response) {
});
};
// -- SCOPED -- //
$scope.selectedItemId = 0;
$scope.items = [
{
"id": 1,
"name": "Amy"
},
{
"id": 2,
"name": "Gi-Anne"
}
];
$scope.onChange = function() {
$scope.onChangeText = "simulated GET triggered.";
self.simulatedGetQuery();
// Use this for actual GET
// self.httpGetQuery
};
// --- //
$scope.onChangeText = "waiting for user input";
$scope.selectedQuery = "no query selected. Chose a person for a valid query.";
}]);
It would need to be fleshed out in a real environment, but I think it will do for a simulated test. Check the scripts in the Plunk for a more detailed perspective on how to do this. All of this is clientside.
The URL of the $http call would be to your backend (MVC or Web API) controller.

ng-init json Object

I use angularjs (ng-init) and I want to assign value to variable as jsonObj.
I try this one but it doesn't work.
ng-init="percentObj = [{ "value":40,"color":"#F5A623" },{ "value":60,"color":"#F5A623" }];
and another question
I want to assign value like
percentObj = [{ "value": parseInt($scope.projectData[0].value),"color":"#F5A623" },{ "value": parseInt($scope.projectData[0].value),"color":"#F5A623" }]
How to fix this problem??
Thx
You can use window object for set your json :
<script type="text/javascript">
window.data= {awesome:1};
</script>
view :
<div ng-controller="myCntrl" ng-init="init('data')">
controller :
function myCntrl($scope) {
$scope.init = function (settings) {
settings = window[settings];
console.log(settings.awesome); //1
};
}
Escape your quotes...
ng-init="percentObj = [{ \"value\":40,\"color\":\"#F5A623\" },{ \"value\":60,\"color\":\"#F5A623\" }];"
Try this...
<body ng-controller="TestController">
<div ng-init="Init()">
{{percentObj || json }}
</div>
</body>
$scope.Init = function()
{
$scope.percentObj = [{ "value":40,"color":"#F5A623" },{ "value":60,"color":"#F5A623" }]
}
Just have a JSON encoded string in some element's attribute and then catch that with Angular.
HTML
<div data-config="{title:'this is my title'}" my-directive></div>
AngularJS:
app.directive('myDirective', function () {
return {
restrict: 'A',
link: function (scope, element) {
// apply config from element's data-config attribute
scope.config = element.data('config');
// print out the data in console
console.log(scope.config);
}
};
});
Can be done without jQuery too, then the .data('config') part changes.
for second one, Please check the code below
var obj = {};
$scope.percentObj = [];
obj.value = parseInt($scope.projectData[0].value);
obj.color = "#F5A623";
$scope.percentObj.push(obj);

BackboneJS - fetching collections from model

I have a JSON file which basically looks like this:
[
{
"First" : [...]
},
{
"Second" : [...]
},
{
"Third" : [...]
},
]
In my router i have:
this.totalCollection = new TotalCollection();
this.totalView = new TotalView({el:'#subContent', collection:this.totalCollection});
this.totalCollection.fetch({success: function(collection) {
self.totalView.collection=collection;
self.totalView.render();
}});
Now i have my Backbone Model:
define([
"jquery",
"backbone"
],
function($, Backbone) {
var TotalModel = Backbone.Model.extend({
url: "/TotalCollection.json",
initialize: function( opts ){
this.first = new First();
this.second = new Second();
this.third = new Third();
this.on( "change", this.fetchCollections, this );
},
fetchCollections: function(){
this.first.reset( this.get( "First" ) );
this.second.reset( this.get( "Second" ) );
this.third.reset( this.get( "Third" ) );
}
});
return TotalModel;
});
and my in my Backbone View i try to render the collection(s):
render: function() {
$(this.el).html(this.template(this.collection.toJSON()));
return this;
}
But I get the Error "First is not defined" - whats the issue here?
Have you actually defined a variable 'First', 'Second' and 'Third'? Based on what you're showing here, there is nothing with that name. One would expect you to have a couple lines like..
var First = Backbone.Collection.extend({});
var Second = Backbone.Collection.extend({});
var Third = Backbone.Collection.extend({});
However you haven't provided anything like that, so my first assumption is that you just haven't defined it.
Per comments, this may be more what you need:
render: function() {
$(this.el).html(this.template({collection: this.collection.toJSON())});
return this;
}
Then..
{{#each collection}}
{{#each First}}
/*---*/
{{/each}}
{{/each}}

Binding the selected value from the DropDownList for MVC View using Razor

I have a View that works but I can not figure out how to get the selected value from the DropDownList:
#model IEnumerable<TRP_MVC_Prototype.Models.usp_TM_Select_ShortNameResult>
#using System.Web;
#using System.Web.WebPages;
#using System.Web.Mvc;
#{
ViewBag.Title = "Details";
}
#using (Html.BeginForm("Details", "ProgramSummary", FormMethod.Post, new { id = "Details" }))
{
<div id="main" style="background-color:White">
<h1 style="background-color:transparent;color:Blue;">
<a>You are logged on as: #ViewBag.Message </a>
<span class="DrpDwnLst">DrpDwnLst</span>
#Html.DropDownList("Short_Title", new SelectList(Model, "short_title", "short_title"), "--Select One--").
#Html.ActionLink("Select","Details",new { Shrt_title = ""})
<a style="color:Blue;position:absolute; right:500px"> #Html.ActionLink("Create Program Summary", "Index", "User_Guide") </a>
<a style="color:Blue;position:absolute; right:250px"> #Html.ActionLink("Edit Program Summary", "Index", "User_Guide")</a>
<a style="color:Blue;position:absolute; right:50px"> #Html.ActionLink("Delete TRP", "Index", "User_Guide")</a>
</h1>
<h1 style="background-color:transparent;color:Blue;">Select TRP to View</h1>
<h1 style="color:Gray";>______________________________________________________________________________________________________________________________________________________________________________</h1>
}
The DropDownList displays correctly but I don't know how to return the Selected value in the ActionLink. In the action link the third parameter passes the value back to the controller it currently has "" but I would like to figure out how to reference the selected value instead.
You can do it with jquery. For changing href from a element you may see this post.
You also need to handle change event for your drop down:
$('#short_title').change(function()
{
// do someting here
});
This is my answer
#Html.DropDownList("short_name", ViewBag.DetailsList as SelectList, "--Select One--", new { onchange = "dofunction(this.form.short_name);" });
function dofunction(dropdown) {
debugger;
for (i = 0; i < 194; i++) {
if (dropdown[i].selected == true) {
var Shrt_ttls = dropdown[i].value.toString()
//document.getElementById("shrtLst").value = Shrt_ttls;
$.ajax({
url: "/ProgramSummary/Details?Shrt_titles=" + Shrt_ttls,
type: 'Post',
data: Shrt_ttls,
success: function(result) {
alert( "Short Name is: " + Shrt_ttls); // process the results from the controller action
},
error: function () {
alert ( "no deal");
}
});
}
}
return true;
}
This returns the value from the javascript function to the HTTPPost for Index.
Thank you,
Bruce