Angularjs ng-repeat does not work if div is moved - javascript

in angularJS I am using ng-repeat to build an list of items. The list is initially in a popup created through kendoui's window. There is a requirement that the popup should be pinnable so I am moving the contents of the div to another div. Works perfectly till now.
After I refresh the array bound with ng-repeat through an ajax call the list becomes empty.
I have created a simple fiddle to show that ng-repeat stops working if div is moved. In the fiddle there is no ajax call so the list does not get empty.
Html:
<p>
<button ng-click="AddInArray()">Add</button>
</p>
<div id="lblDiv">
<label ng-repeat="item in itemsArray | orderBy:'toString()'">{{item}}-{{$index}}:</label>
</div>
<button id="btn" ng-click="btn_click()">Move</button>
<div id="container">
</div>
JS:
$scope.itemsArray = ["Test"];
$scope.AddInArray = function() {
this.itemsArray.push("Test");
}
$scope.btn_click = function() {
var html = $("#lblDiv").html();
$("#container").html(html);
$("#lblDiv").html("");
}
Here is the fiddle

I have corrected your fiddle here.
Basically, you had to change this:
$scope.btn_click= function(){
var html = $("#lblDiv");
$("#container").append(html);
$("#lblDiv").remove(html);
};
Or, which is just the same, but in one line:
$("#lblDiv").appendTo("#container");
Glad to help!

You've emptied the template.
$("#lblDiv").html("");
Should be:
$scope.itemsArray = ["Test"];
Fiddle
If you want to actually move the div replace the entire function with:
$("#lblDiv").appendTo("#container");
Fiddle

Add this one it might help you
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.name = 'Superhero';
$scope.itemsArray = ["Test"];
$scope.AddInArray = function() {
this.itemsArray.push("Test");
};
$scope.btn_click= function(){
var html = $("#lblDiv");
$("#container").html(html);
$("#lblDiv").append("");
};
}

Related

Get the background color of div - AngularJs?

I want to get the background color of a DIV element when I click on that div.
HTML -
<div style="background-color:red" ng-click="getFilter($event)" class="agenda col-md-4">ABCDEGF/div>
JS Controller -
$scope.getFilter = function(event){
};
If we do in in jQuery, It would have been done as -
$('div').click(function(){
$color = $(this).css('background-color');
});
But I want to do with angularJs. Someone help ?
you can use:
$scope.getFilter = function(event) {
$scope.color = $(event.currentTarget).css('background-color');
};
You could use ng-style for setting color dynamically, I'd just have it inside the API response for each record. I assumed that you are rendering all the elements using ng-repeat directive.
Markup
<div ng-repeat="item in items"
ng-style="{'background-color': item.color}"
ng-click="getFilter(item);"
class="agenda col-md-4">
ABCDEGF
</div>
Code
$scope.getFilter = function(item){
$color = item.color;
}
Created sample example with service to get and assign color dynamically. JSFiddle - https://jsfiddle.net/q16fcq99/
Modify the service with your required call. Hope this will help.
<body ng-app="SampleApp">
<div ng-controller="fcController">
<div ng-style="{'background-color': divColor}" ng-click="getFilter($event);" class="agenda col-md-4">
ABCDEGF
</div>
</div>
</body>
var sampleApp = angular.module("SampleApp", []);
sampleApp.controller('fcController', function($scope, colorService) {
$scope.divColor = 'red';
$scope.getFilter = function(event) {
$scope.divColor = colorService.getColor();
console.log('Event Fired');
};
});
sampleApp.service('colorService', function() {
this.getColor = function() {
return "blue"; //Call Actual Service to Get Color
};
});

Strange jQuery behaviour while showing hiding contents

I have a series of html contents called filters which is generated from database. The contents can change dynamically according to the page. I have given css IDs to each main div and appended a number with them while looping. Below is a sample snippet:
<div><a id="filter-1">Brands</a></div>
<div id="filter-op-1">This is option 1</div>
<div><a id="filter-2">Size</a></div>
<div id="filter-op-2">This is option 2</div>
<div><a id="filter-3">Color</a></div>
<div id="filter-op-3">This is option 3</div>
the ids filter-1 and filter-op-1 and so on are generated by the number of loops, so we dont know how much contents on the page will be generated for the filters.
I need to show/hide the filter-op-x contents by a click, so i wrote the following jQuery code:
$(document).ready(function () {
$('div a').click(function() {
var self = $(this);
var cssId = self.attr('id');
var child = $('div#filter-op-'+cssId);
child.toggle();
});
});
Now the problem is that it is not working in this way, but if i remove the cssId in js code and -1, -2 etc in html, it start working, but it is hiding all contents no matter which a i clicked.
I dont understant what is causing this issue. Anybody can explain this problem and give some good advice how to handle it?
JsFiddle is here
Thanks
You need to make some changes in your JS code like this:
$(document).ready(function () {
$('div a').click(function() {
var self = $(this);
var cssId = self.attr('id');
console.log(cssId); // This gives the `a` id.
var id = cssId.split("-")[1]; // Split and get the number part
console.log(id);
var child = $('div#filter-op-'+id); // append the number part here
child.toggle();
});
});
The fiddle: https://jsfiddle.net/sandenay/uk1Lquuh/1/
Problem found :
your cssId always return filter-1, filter-2, filter-3
and child become as 'div#filter-op-'+cssId) ==> 'div#filter-op-filter-1 which is produce wrong id of child div.
I have added extra data attribute
Here is my working code:
HTML :
<div><a id="filter-1" data="1">Brands</a></div>
<div id="filter-op-1">This is option 1</div>
<div><a id="filter-2" data="2">Size</a></div>
<div id="filter-op-2">This is option 2</div>
<div><a id="filter-3" data="3">Color</a></div>
<div id="filter-op-3">This is option 3</div>
JS :
$(document).ready(function () {
$('div a').click(function() {
var self = $(this);
var cssId = self.attr('data');
var child = $('div#filter-op-'+cssId);
child.toggle();
});
});
updated JSFIDDLE example

How to change attribute of html in angular js?

I want to change attribute of a div in angularjs. I know how to do in jquery but not in angular.
html :
<div ng-app="test">
<div ng-controller="cont">
<button ng-click="updateStatus()">TOGGLE ATTRIBUTE </button>
<div id="test" {{status}}>TEXT </div>
</div>
</div>
js :
var angApp = angular.module('test',[]);
angApp.controller('cont', ['$scope', function($scope){
$scope.status = 'someattr';
$scope.updateStatus = function() {
if( $scope.status == 'someattr'){
$scope.status = '';
}else{
$scope.status = 'someattr';
}
};
}])
Here is jsfiddle to work with.
In jquery :
var div = $('#test');
$('button').on('click',function(){
if( div.attr('someattr'){
div.removeAttr('someattr');
}else{
div.attr('someattr',true);
}
})
I want to achive same in angularjs.
NOTE : I AM NOT TRYING TO ADD DISABLED STATE TO DIV. I JUST WANT TO TOGGLE AN ATTRIBUTE.
In your specific case (add disabled attribute), you have to use ng-disabled in order to bind its value to a $scope variable.
It makes no sense to use it on a div, I'll use a button instead to give you an example:
<button ng-click="updateStatus()">TOGGLE ATTRIBUTE </button>
<button id="test" ng-disabled='status'>TEXT</button>
see a working example HERE
UPDATE
To toggle an attribute, yo can use attr() and removeAttr():
el.attr("disabled", "true");
el.removeAttr("disabled");
See a complete example HERE
NOTE (thanks to jme11): as reported on Angular Dev Guide
Do not use controllers to:
Manipulate DOM — Controllers should contain only business logic. Putting any presentation logic into Controllers significantly affects its testability. Angular has databinding for most cases and directives to encapsulate manual DOM manipulation.
you should avoid to manipulate the DOM inside the controller.
Make a directive which uses .attr and .removeAttr in a $watch handler. Here's a modified version of your fiddle: http://jsfiddle.net/0eqz1qo1/1/
The directive:
.directive('addAttr', function() {
return function(scope, elem, attr) {
scope.$watch(attr.addAttr, function(val, prev) {
if(val)
elem.attr(val, "");
if(prev && prev !== val)
elem.removeAttr(prev);
});
}
})
Usage:
$scope.myVar = 'hello';
...
<div add-attr="myVar"></div>
becomes:
<div add-attr="myVar" hello></div>
You can not implement disable property for any div.But you can hide or show the div using Angular.js.Check the code below.
<div ng-app="test">
<div ng-controller="cont">
<button ng-click="updateStatus()">TOGGLE ATTRIBUTE </button>
<div id="test" ng-hide="hide-div" >TEXT </div>
</div>
</div>
JS:
var angApp = angular.module('test',[]);
angApp.controller('cont', ['$scope', function($scope){
$scope.hide-div = true;
$scope.updateStatus = function() {
if( $scope.hide-div == true){
//do something here
}else{
$scope.hide-div = true;
}
};
}])
Other option is you can also use ng-class in div and inside those class you can declare display:none,display:block
You can't add an attribute by this way with angularJS. If you inspect your code, you can see that the attribute that you're trying to pass in div is {{status}}(your expression), use existing attributes rather than create your own! For example: ng-disabled, ng-show, ng-hide.
It's not really right thing to do. I guess, cannot inject attribute with angularJS. {{status}} is an expression, it's like expression and will evaluate by angularjs while rendering to html. about expression: https://docs.angularjs.org/guide/expression
Replace your line :
<div id="test" {{status}}>TEXT </div>
with these :
<div id="test" someattr="" ng-if="status=='someattr'" >TEXT</div>
<div id="test" ng-if="status==''" >TEXT</div>

Removing elements from a DIV, and previously inserted values Issue

I was having an issue earlier cloning some HTML within a page I have now resolved the issue using the following JS Fiddle Below:
HTML:
<div id='1'>
<div class="template"> <!-- mark a clone target -->
...
</div>
<div>
<input type="button" name="addNewRow" value="Add Row" />
</div>
</div>
JS:
var $template = $('.template');
$('input[type=button]').click(function() {
$template.clone().insertAfter($template);
});
Demo: http://jsfiddle.net/VcBrz/
EDIT** the first issue I had with cloning and clearing textboxes has been resolved resolved.
If you refer to the JSFiddle above - a new row is added every time a button is clicked on a form.
I am hoping to add another button to achieve the exact opposite, so rows can be removed on button click, and was wondering whether anyone could suggest an answer?
Try the following
var $template = $('.template');
$('#add').click(function() { // where add is the id of add button
$template.clone().insertAfter($template).find("input:text").val("");
});
$('#remove').click(function() { // where remove is the id of remove button
if($('.template').length>1)
$('.template').last().remove();
});
check this JSFiddle
Check this fiddle
var $template = $('.template');
$('input[type=button]').click(function() {
$template.clone().insertAfter($template).find("input:text").val("");
});
Reference : clear text field value in clone object
Updated Fiddle
var $template = $('.template');
$('input[name=addNewRow]').click(function() {
$template.clone().insertAfter($template).find("input:text").val("");
});
$('input[name=removeRow]').click(function() {
$('.template').filter(":not(:first-child)").get(-1).outerHTML = "";
});

Change text color dynamically AngularJS

I struggle thinking "The Angular Way" so this is undoubtedly a simple problem, but I'm trying to have it so when I click a button (which will eventually be colored) the text changes to that color. Here is essentially the code:
JS
var myApp = angular.module('myApp', []);
myApp.controller('ColorCtrl', ['$scope', function($scope){
$scope.changeColor = function(value){
return {"color:" value };
}
$scope.turnGreen = function (){
//what to do here?
}
$scope.turnBlue = function() {
//and here?
}
}]);
HTML
<div ng-app="myApp" ng-controller="ColorCtrl">
<button ng-click="turnBlue()">Make text blue</button>
<button ng-click="turnGreen()">Make text green</button>
<p ng-style="changeColor(value)">I should be either green or blue!</p>
</div>
I know I could easily use jQuery to select the text I want to work with, but I don't want to do that. Do i need to give my paragraph a model? Any push in the right direction is greatly appreciated - thank you.
You could do this way:
Define ng-class directive and value as colorClass which will be set in the scope.
<p ng-class="customStyle.colorClass">I should be either green or blue!</p>
and do:
$scope.customStyle = {};
$scope.turnGreen = function (){
$scope.customStyle.colorClass = "green";
}
$scope.turnBlue = function() {
$scope.customStyle.colorClass = "blue";
}
and some rules:
.green{
color:green;
}
.blue{
color:blue;
}
or with inline style
<p ng-style="customStyle.style">I should be either green or blue!</p>
and
$scope.customStyle = {};
$scope.turnGreen = function (){
//what to do here?
$scope.customStyle.style = {"color":"green"};
}
$scope.turnBlue = function() {
$scope.customStyle.style = {"color":"blue"};
}

Categories