Changing the CSS of a div in AngularJS directive - angularjs

I have a problem I have created a directive which is doing ng-repeat on an array of objects
---Showing the value on gui------
Now I want that if I click on any div of this repeat that particular div's background color should change
I have tried something like this
link:function(scope,element,attributes){
$(element).on('click',function(e){
$(element).addClass('A');
$(element).removeClass('B');
})
}

You can use the ng-class directive to apply classes on specific occurences, in your case in combination with the ng-click:
<div ng-repeat="item in items"
ng-class="{A: item.clicked, B: !item.clicked}"
ng-click="item.clicked = !item.clicked">
<!-- .. content -->
</div>
See this jsfiddle for example

You can try something like this, but this will need more workaround.
<div ng-click=“changeBackground($event)”></div>
// In Controller
$scope.changeBackground = function(event){
event.target.style.background = “#000”;
}
It would be better if you can submit your code.

Related

How to access nested elements in AngularJS

I have a list of items (divs) with a button. When I click on one of this buttons I can access the element using
$event.currentTarget
that returns some thing like
<div ng-click="myFunc()">
<i class="someclass"></i>
<span>bla bla</span>
</div>
how can I access and elements to modify attributes like class?
Don't. Use existing directives like ng-class or ng-if, etc in your html templates.
<div ng-click="clicked = true">
<span ng-class="{'someclass': clicked}">bla bla</span>
</div>
See stackblitz
Although you can get the html dom element and edit it you should only do this as a last option and other angularjs supported methods have failed or are not supported.
template
<div ng-click="myFunc($event)">
<i class="someclass"></i>
<span>bla bla</span>
</div>
controller
$scope.myFunc(event) {
var elem = angluar.element(event.currentTarget);
elem.children(".someclass").removeClass("someclass")
}

onclick on hyperlink should add a div horizontally using angularjs

My html:
<div id="contentDiv">
<div id="headerDiv" ><div id="titleDiv"> Queries</div></div>
<div id="valuesDiv" ><div id="yearDiv"> 2015</div></div>
<div id="graphDiv" ><div id="chartDiv">graph</div></div>
</div>
Like this div, I have another div but the content in the div is different.
How to add a new div horizontally when I click on hyperlink using angularjs?
How can I do this? please help me out regarding this
Looks like what you need is a two way binding with the ng-model directive. So the idea would be that you bind the new div to a variable in your scope which is initially in an empty or undefined state (for example, there are better ways). When the hyperlink is clicked it calls the function specified by an ng-click directive which will fill your bound object, which in turn will cause the new div to be rendered.
EDIT:
Based on your comments here is a simple example.
HTML page:
<div id="newDiv" ng-repeat="item in items">
<!-- Div content -->
<!-- example -->
<input type="text" ng-model="item.name">
</div>
<input type="button" ng-click="addItem()">
Controller:
$scope.items=[];
$scope.addItem = function() {
var newItem = {};
newItem.name = "new item name";
$scope.items.push(newItem);
}
What's happening here is the data for each div is stored in an array of objects. The ng-repeat directive will repeat the div for each object in the array. You can then fill the elements in the div using the object. Adding a new div is as simple as adding a new item to the array and angular will take care of the rest for you. Please note that I have not tested this example, but hopefully it's enough to point you in the right direction.
RE aligning the divs horizontally, this will be done with CSS, using the inline-block display mode. So you could give the div a class of, for example, "horizontalDiv" and add the following class to your CSS file:
.horizontalDiv {
display: inline-block;
}

AngularJS: create element dynamically

How do I go about create an element in my controller? e.g. on a click event?
example controller:
function AddCtrl($scope){
$scope.add = function(){
// do stuff to create a new element?
}
}
example view:
<div ng-controller="AddCtrl">
<button ng-click="add()">Add</button>
// create <input type="text" ng-model="form.anotherField">
</div>
Any suggestions much appreciated.
AngularJS is intended to follow MVC - so the controller creating an element in the view doesn't agree with the MVC behavior. The controller should not know about the view.
It sounds as if you want to have a control appear based on some conditional logic. One approach would be to bind to the visibility of the element.
In Angular, your controllers should not be manipulating the DOM directly. Instead, you should describe the elements you need in your templates, and then control their display with directives, like ng-switch, ng-hide / ng-show, or ng-if, based on your model, ie, your data.
For example in your controller you might do something like:
$scope.showForm = false;
And then in your partial:
<div id="myForm" ng-show="showForm">
<!-- Form goes here -->
</div>
By switching $scope.showForm between true and false, you will see your myForm div appear and disappear.
This is a classical mistake coming from jQuery moving to Angular or any other MVC library. The way you should think is to let the view react to changes in the scope.
$scope.items = []
$scope.add = function(){
$scope.items.push({});
}
In the view:
<input type="text" ng-repeat="item in items" ng-model="item.property">
If you want to display an element based on some condition or after the click, use ng-switch: http://docs.angularjs.org/api/ng/directive/ngSwitch
If you want to add multiple elements, create a repeated list of items and add an item to your view-model on clicking the button:
$scope.yourlistofitems = [];
$scope.add = function() {
$scope.yourlistofitems.push("newitemid");
}
And in the HTML:
<input type="text" ng-repeat="item in yourlistofitems" ng-model="item.property">

Angularjs: custom grid component, dynamically add <br> elements

Ok, I have made a really simple grid component. I fetch a column count attribute and add a <br> tag after the end of a row. I do that within the link function.
Her is the directive: http://pastebin.com/U4ckuKJw
grid.html just looks like this: <div class="grid" data-ng-transclude=""></div>
In my first example I have 7 <div> tags inside the grid component and want to have 3 columns. So after every third <div> I want a <br> to be added.
It looks like this and is working:
<div data-grid="" data-cols="5">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
</div>
This one is not working: http://pastebin.com/wtcgM2Hv
I think it is because of the directive ng-repeat and that the content of the grid component isn't rendered at the time the link function ist executed.
Any thoughts on how to solve this problem or how to optimise the component?
An easier approach may be to solve the problem with standard angular directives and css. For instance, if you float your cells and clear: left on those cells that start a new row, you can use ng-repeat and ng-class to accomplish this.
I created an example at: http://jsbin.com/idukaz/1
The html looks like this. Note I'm using ng-class to apply the class that formats the cell that needs to start a new row depending on the result of calling the custom columnEnd function. columnBreak is a scope variable for the number of columns you want. $index is a variable generated by ng-repeat:
<div class="table">
<div class="label"
ng-class="{'new-row': startNewRow($index, columnBreak) }"
ng-repeat="item in items">{{ item.name }} ({{ $index + 1 }})</div>
</div>
In your controller:
app.controller('Controller', ['$scope', function (scope) {
// list of grid data
scope.items = [];
// controls the number of columns
scope.columnBreak = 5;
// calculates if current cell is start of new row
scope.startNewRow = function (index, count) {
return ((index) % count) === 0;
};
}]);
In your css if you float your cells and clear left, you'll get your columns to dynamically
reformat when you change the columnBreak value.
.label {
float: left;
}
.new-row {
clear: left;
}
Ok, now I found the solution:
use angular directive to change classes of ng-repeat elements
I mixed it with Marks idea and manipulate the css classes now.
Thanks

How to get AngularStrap active tab?

I am somewhat new to using Angular and AngularStrap directives. I need to use the tab directive with static markup like the example:
<div data-fade="1" bs-tabs>
<div data-title="'Home'"><p>Static tab content A</p></div>
<div data-title="'Profile'"><p>Static tab content B</p></div>
</div>
On another part of the page I would like to display a div only when the first tab is selected. The div is not part of the tabs, but is in the same overall controller. How can I show/hide this div based on the selected tab?
Something like this?
<div ng-show="???? active tab stuff here ????">Home tab is selected</div>
Thanks for any help.
As shown in the example on the AngularStrap page the active tap is stored in
tabs.activeTab
So you can use this property to conditionally show display something else like so
<div ng-show="tabs.activeTab == 0">The first tab is active</div>
UPDATE
Even with non object tabs you can just bind a model against the bs-tabs to store the active ID like so:
<div data-fade="1" ng-model="tabs.activeTab" bs-tabs>
Here is an updated plnkr. (Click on the 3rd tab and see the 'Test' text appear)
I found somewhat of a hack to resolve this issue for now. This does not seem like the best approach, so if someone has a better idea, please share.
I realized that the bsTabs directive is creating data-toggle attributes for each tab. By watching the data-toggle shown event, I am able to recognize the tab change and display the div. The controller code looks like this:
$scope.HomeTabSelected = true;
function watchTab() {
$('a[data-toggle="tab"]').on('shown', function (e) {
$scope.$apply($scope.HomeTabSelected = (e.target.innerHTML == "Home"));
})
}
setTimeout(watchTab, 2000); // setTimeout necessary to allow directive to render
and the HTML div uses ng-show.
<div ng-show="HomeTabSelected">Home tab is selected</div>

Resources