Angular add class to active element - css

How i can add active class to menu with angular with this case
html code
<div class="categories" ng-controller="CategoryController">
<ul class="menu">
<li ng-repeat="category in categories">
<a ng-click="sendCategory(category)">{{category.name}}</a>
</li>
</ul>
</div>
js code
myApp.factory('Categories', ['$http',
function ($http) {
return {
get: function (callback) {
$http.get('data/categories.json').success(function (data) {
callback(data);
})
}
}
}
]);

use this syntax:
<ul class="menu" ng-class="{classname: variableFromScope}">
Set this variable to true or false (to activate or disactivate your classname class) in your controller where it needed:
$scope.variableFromScope = true;

here is solution
html code
<ul class="menu">
<li ng-repeat="category in categories"><a ng-click="sendCategory(category)" ng-class="{ active: activePath=='/{{category.name}}' }">{{category.name}}</a>
</li>
</ul>
js code
`
myApp.controller('CategoryController', function ($scope, $route, $location, $http, Categories){
Categories.get(function (response) {
$scope.categories = response;
});
$scope.sendCategory = function (category) {
$location.path(category.name);
};
$scope.activePath = null;
$scope.$on('$routeChangeSuccess', function () {
$scope.activePath = $location.path();
console.log($location.path());
});
})`

Related

Trying to display data from an object to an unordere list. Nothing Showing

searchresults is an object(json data) Im trying to show the data in an unordered list. Nothing is showing up. Not sure why.. Ive set the json data in a session, like Session.set("searchresults", data); the data is saved and doing a console.log(console.log(searchresults[0].snippet.title); works.
searchList = React.createClass({
renderSearches() {
var searchresults = Session.get('searchresults');
return
Object.keys(searchresults).map(function (key) {
return <SearchItem search={searchresults[key]} />;
});
},
render: function() {
return (
<div>
<ul>
{this.renderSearches()}
</ul>
</div>
);
}
});
SearchItem = React.createClass({
render: function() {
return (
<li > <strong>{this.props.search.snippet.title}</strong> </li>
);
}
})
I think you forgot to return SearchItem.
return <SearchItem search={searchresults[key]} />
In addition to the Road answer's, in your SearchItem, you can't access to searchresults[key].
If you say:
<SearchItem search={searchresults[key]} />;
You have to use the props of your SearchItem component.
SearchItem = React.createClass({
render: function() {
return (
<li><strong>{this.props.search.snippet.title}</strong> </li>
);
}
});

ASP.NET tab using bootstrap turn back to the active tab after DataGrid Paging?

I have problem when using bootstrap tab that included in ASP.NET Admin Template Siminta . Whenever I hit the next tap with postback event it will be back to the active tab. I try many solution but in vain. asp.net bootstrap Keep current active tab after post-back event
<ul class="nav nav-pills">
<li class="active">
<i class="fa fa-home"></i> Profile
</li>
<li>
<i class="fa fa-leanpub"></i> Education
</li>
</ul>
............
<div class="tab-content">
<div class="tab-pane fade in active" id="EmpProfile">
.........
</div
</div>
And the code in bootstrap :
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
this.element = $(element)
}
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var previous = $ul.find('.active:last a')[0]
var e = $.Event('show.bs.tab', {
relatedTarget: previous
})
$this.trigger(e)
if (e.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.parent('li'), $ul)
this.activate($target, $target.parent(), function () {
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: previous
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& $active.hasClass('fade')
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu')) {
element.closest('li.dropdown').addClass('active')
}
callback && callback()
}
transition ?
$active
.one($.support.transition.end, next)
.emulateTransitionEnd(150) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
var old = $.fn.tab
$.fn.tab = function ( option ) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
// $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
// e.preventDefault()
// $(this).tab('show')
// })
$('[data-toggle="tab"],[data-toggle="pill"]').click(function () {
$(this).parent().children('.active[data-toggle="tab"],.active[data-toggle="pill"]').removeClass('active');
$(this).addClass('active');
});
}(jQuery);
So, how can I fix it?
I followed this instruction, but it still does not work: Bootstrap Tabs Maintain Selected (Active) Tab on PostBack in ASP.Net ,using the same bootstrap version the difference is only I use the DataGrid with Paging , whenever I go to next tab, click the page of DataGrid then it goes back to Active Tab (the first one):
Adding :
<asp:HiddenField ID="TabName" runat="server" />
Then use this script:
<script type="text/javascript">
$(function () {
var tabName = $("[id*=TabName]").val() != "" ? $("[id*=TabName]").val() : "EmpProfile";
$('#Tabs a[href="#' + tabName + '"]').tab('show');
$("#Tabs a").click(function () {
$("[id*=TabName]").val($(this).attr("href").replace("#", ""));
});
});
</script>
Then, put the behind code:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
TabName.Value = Request.Form[TabName.UniqueID];
}
}
And I also not forget to add this :
protected void grdEmployee_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
grdEmployee.CurrentPageIndex = e.NewPageIndex;
TabName.Value = Request.Form[TabName.UniqueID];
BindGrid();
}
}
<!--Basic Tabs -->
<ul class="nav nav-pills">
<li class="active">
<i class="fa fa-home"></i> Profile
</li>
.............
</ul>
<div class="tab-content">
<div class="tab-pane fade in active" id="EmpProfile">
<asp:UpdatePanel ID="updatePanelEmployee" runat="server">
<ContentTemplate>
<asp:Datagrid ID="grdEmployee" runat="server" ..................
</asp:Datagrid>
</ContentTemplate>
</asp:UpdatePanel>
It works!

Passing value from view to a controller

I have this helper code
#helper GetTreeView(List<MvcTreeview.Models.Category> siteMenu, int parentID)
{
foreach (var i in siteMenu.Where(a => a.ParentID.Equals(parentID)))
{
<li>
#{var submenu = siteMenu.Where(a => a.ParentID.Equals(i.ID)).Count();}
#if (submenu > 0)
{
<span class="collapse collapsible"> </span>
}
else
{
<span style="width:15px; display:inline-block"> </span>
}
<span id="Category">
#i.CategoryName
<b></b>
</span>
#if (submenu > 0)
{
<ul>
#Treeview.GetTreeView(siteMenu, i.ID)
#* Recursive Call for Populate Sub items here*#
</ul>
}
</li>
}
}
and i want to pass the id to a Action method of a controller.
How to pass the id from view to a action method in controller.
$('#Category').click(function () {
url = '#Url.Action("Index", "TestDetails");
$.ajax({
url: url,
type: 'POST',
success: function (returnData) {
},
error: {
}
});
});
How can i get the id in the second snippet of code.
Using that id i have to fetch some details using a action method in my controller.
Action Method
public ActionResult Index(int id)
{
TestDetail detail = new TestDetail();
detail = db.TestDetails.Single(a => a.ID == id);
return View(detail);
}
simply pass "this" to your onclick function
<span class="Category">
#i.CategoryName
<b></b>
</span>
Javascript: (Edited)
<script type="text/javascript">
function CategoryClick(clicked_id)
{
alert(clicked_id);
url = '#Url.Action("TestDetails", "Index")'; //Url.Action(actionName, ControllerName)
$.ajax({
url: url,
data: {id: clicked_id}, //json format
success: function (returnData) {
},
error: {
}
});
}
</script>
Edit your helper as following:
#helper GetTreeView(List<MvcTreeview.Models.Category> siteMenu, int parentID)
{
foreach (var i in siteMenu.Where(a => a.ParentID.Equals(parentID)))
{
<li>
#{var submenu = siteMenu.Where(a => a.ParentID.Equals(i.ID)).Count();}
#if (submenu > 0)
{
<span class="collapse collapsible"> </span>
}
else
{
<span style="width:15px; display:inline-block"> </span>
}
<span >
<a class="Category" href="#" id="#i.ID">#i.CategoryName</a>
<b></b>
</span>
#if (submenu > 0)
{
<ul>
#Treeview.GetTreeView(siteMenu, i.ID)
#* Recursive Call for Populate Sub items here*#
</ul>
}
</li>
}
}
and the ajax call:
$('.Category').click(function () {
url = '#Url.Action("Index", "TestDetails")';
$.ajax({
url: url,
type: 'POST',
data: "{'id': " + $(this).attr("id") + "}",
success: function (returnData) {
},
error: {
}
});
});

Onclick event for li with javascript in asp.net mvc

<ul>
#foreach (var item in Model.Users.Where(s => s.DepartmentId == 3))
{
<li>
#Ajax.ActionLink(item.UserName, "Index", new { item.Id }, new AjaxOptions() { HttpMethod = "Get" });
</li>
}
</ul>
How can ı get item.Id if i onclick item.username with javascript ?
I thought give to attribute to "li onclick".but i dont know there is better solution here or not ?
You could use a standard link and data-* attribute:
<ul>
#foreach (var item in Model.Users.Where(s => s.DepartmentId == 3))
{
<li>
#Html.ActionLink(
item.UserName,
"Index",
new { id = item.Id },
new { #class = "myLink", data_id = item.Id }
)
</li>
}
</ul>
and then in a separate javascript file:
$(function() {
$('.myLink').click(function() {
// get the id:
var id = $(this).data('id');
alert(id);
// now you can send the AJAX request
$.get(this.href);
// cancel the default action of the link
return false;
});
});

emberjs router class active

I know i can find examples of this but i cant put it into my code without errors... just dont know why.
I want start with set class="menu-active" to first in menu.
<li><a {{action gotoAbout}} >About</a></li>
And later when somebody click other position of menu move class="menu-active" to this position.
http://jsfiddle.net/kwladyka/LGArM/3/
And the bonus question: Do you have any remarks to make my code better?
HTML
<script type="text/x-handlebars" data-template-name="application">
{{view App.NavbarView}}
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="navbar">
<div id="menu" class="grid_12">
<ul>
<li><a {{bindAttr class="isAbout:active"}} {{action gotoAbout}} >About</a></li>
<li><a {{bindAttr class="isProjects:active"}} {{action gotoProjects}} >Projekty</a></li>
<li><a {{action gotoTechnology}} >Technologie</a></li>
<li><a {{action gotoContact}} >Kontakt</a></li>
</ul>
</div>
</script>
EMBERJS
$(function() {
console.log("### emberjs start ###");
App = Em.Application.create({
rootElement: '#emberjs-container'
});
App.ApplicationController = Em.Controller.extend();
App.ApplicationView = Em.View.extend({
templateName: 'application'
});
App.NavbarController = Em.Controller.extend({
});
App.NavbarView = Em.View.extend({
templateName: 'navbar',
});
App.AboutView = Em.View.extend({
templateName: 'about'
});
App.ProjectsView = Em.View.extend({
templateName: 'projects'
});
App.TechnologyView = Em.View.extend({
templateName: 'technology'
});
App.ContactView = Em.View.extend({
templateName: 'contact'
});
App.Router = Em.Router.extend({
enableLogging: true,
location: 'hash',
root: Em.Route.extend({
// EVENTS
gotoAbout: Ember.Route.transitionTo('about'),
gotoProjects: Ember.Route.transitionTo('projects'),
gotoTechnology: Ember.Route.transitionTo('technology'),
gotoContact: Ember.Route.transitionTo('contact'),
// STATES
about: Em.Route.extend({
route: '/',
connectOutlets: function (router, context) {
router.get('applicationController').connectOutlet('about');
}
}),
projects: Em.Route.extend({
route: '/projects',
connectOutlets: function (router, context) {
router.get('applicationController').connectOutlet('projects');
}
}),
technology: Em.Route.extend({
route: '/technology',
connectOutlets: function (router, context) {
router.get('applicationController').connectOutlet('technology');
}
}),
contact: Em.Route.extend({
route: '/contact',
connectOutlets: function (router, context) {
router.get('applicationController').connectOutlet('contact');
}
})
})
});
App.initialize();
});

Resources