reuse function in angularjs - javascript

I've this easy code that works fine.
html snippet:
<div class="iconbar" ng-controller="icons">
<span ng-click="iconclk()">icon</span>
<div ng-if="icon1">value</div>
</div>
and the js:
app.controller('icons', function($scope)
{
$scope.icon1 = false;
$scope.iconclk = function(){
if(!$scope.icon1) $scope.icon1 = true;
else $scope.icon1 = false;
};
});
now the problem is that i wont to pass icon1 as a parameter in iconclk to use the same function with multiple icons (icon1,icon2,icon3...)
I've tried this:
html:
<div class="iconbar" ng-controller="icons">
<span ng-click="iconclk(icon1)">icon</span>
<div ng-if="icon1">value</div>
</div>
and the js:
app.controller('icons', function($scope)
{
$scope.icon1 = false;
$scope.iconclk = function(icon){
if(!icon) icon = true;
else icon = false;
};
});
But doesn't work. some help please? thanks in advance!

The main problem is that you're passing by value, so modifying icon will not change icon1. Instead, I would change your icon variables to an array and reference by index:
<div class="iconbar" ng-controller="icons">
<span ng-click="iconclk(1)">icon</span>
<div ng-if="icon[1]">value</div>
</div>
Others will be iconclk(2)&icon[2], iconclk(3)&icon[3], and so on...
Controller:
app.controller('icons', function($scope) {
$scope.icon = [false, false, false]; // or just [] if you want it to be simple
$scope.iconclk = function(icon) {
$scope.icon[icon] = !$scope.icon[icon];
};
});

Related

Loading data in details modal using AngularJS

I'm trying to load data into modal using AngularJS. I did the load the data into a list of "cards" and it works fine. But, to each card, I need to open a details modal and to load the rest of the data within it. Follow my code:
//Part of index.html
<body ng-controller="CardsController">
<div class="container">
<div class="cards" ng-repeat="card in cards">
<h3>{{card.user}}</h3>
<button type="button" name="play" title="play" ng-click="toggleModal(card)">Play</button>
</div>
</div>
<my-modal show='modalShown' width='250px' height='40%'>
<h3>{{card.user}}</h3> <-- here is my problem!
</my-modal>
// js/controllers/cards-controller.js
angular.module('angstudy').controller('CardsController', function($scope, $http){
$scope.cards = [];
$http.get('http://localhost:3000/api/persons')
.success(function(retorno){
console.log(retorno);
$scope.cards = retorno;
})
.error(function(erro) {
console.log(erro);
});
$scope.modalShown = false;
$scope.toggleModal = function(card) {
$scope.modalShown = !$scope.modalShown;
};
});
// js/directives/modal-dialog.js
angular.module('modalDialog', [])
.directive('myModal', function() {
var ddo = {};
ddo.restrict = "E";
ddo.transclude = true;
ddo.scope = {
user: '#user',
show: '='
};
ddo.link = function(scope, element, attrs) {
scope.dialogStyle = {};
if (attrs.width)
scope.dialogStyle.width = attrs.width;
if (attrs.height)
scope.dialogStyle.height = attrs.height;
scope.hideModal = function() {
scope.show = false;
};
};
ddo.templateUrl = 'js/directives/modal-dialog.html';
return ddo;
});
// js/directives/modal-dialog.html (template for the directive)
<div class='ng-modal' ng-show='show'>
<div class='ng-modal-overlay' ng-click='hideModal()'></div>
<div class='ng-modal-dialog' ng-style='dialogStyle'>
<div class='ng-modal-close' ng-click='hideModal()'>X</div>
<div class='ng-modal-dialog-content'></div>
</div>
</div>
// js/main.js
angular.module('angstudy', ['modalDialog']);
The cards are been displayed normally and the modal opens, but does not display the AE values within the modal (in this case, I'm just testing the value "user", but the json has more data). If I insert just a static value, it displays...
I would've done it by keeping the modal html in a separate file and using a separate controller and I would pass the data to the Modal controller with the resolve keyword.
But since you are using the same controller on both the templates. You can keep a separate variable called $scope.SelectedCard to achieve the functionality.
In your toggleModal method you can assign the card as:
$scope.toggleModal = function(card) {
$scope.modalShown = !$scope.modalShown;
$scope.selectedCard = card;
};
and in the modal you can change to:
<my-modal show='modalShown' width='250px' height='40%'>
<h3>{{selectedCard.user}}</h3> <-- problem solved
</my-modal>

AngularJS ng-show when some value is true

I want to display one symbol (🗸) when one or more of the values in a scope ($filter.producers) is set to true, and another one (X) when all the values are false. I am trying to do show with ng-show, but I cannot find the way to make it work.
My html goes like this:
<div ng-app="myApp" ng-controller="Ctrl">
{{ctrlTest}}
<span ng-show="filter.producers == false">X</span>
<span ng-show="filter.producers != false">🗸</span>
<hr/>
<div ng-repeat="elements in filter">
<div>
<li ng-repeat="(key,value) in filter.producers" ng-show="value">{{key}}
<a ng-click="filter.producers[key]=false"> X</a>
</li>
</div>
{{filter.producers}}
</div>
</div>
And my controller:
angular.module('myApp', [])
.controller('Ctrl', function($scope) {
$scope.ctrlTest = "Filters";
$scope.filter = {
"producers": {
"Ford": true,
"Honda": true,
"Ferrari": true
}
}
});
Here is a working plunker
Thanks in advance!
The value of filter.producers in your case, is this object: {"Ford": true, ..}. It certainly will not equals to true or false! If I get you question correctly, what you should do is plucking all it's value and check if any of these value is true or false, something like this:
//In your controller
$scope.anyProducerTrue = function() {
var anyTrue = false;
angular.forEach($scope.filter.producers, function(value, key) {
if (true == value) anyTrue = true;
});
return anyTrue;
}
//In your view
<span ng-show="!anyProducerTrue()">X</span>
<span ng-show="anyProducerTrue()">🗸</span>
you need another function to check all properties are true or false initially and when click (X) link to set false for a specific property and do not need two ng-repeat in your DOM. you can try my solution.
like:
your controller:
angular.module('myApp', [])
.controller('Ctrl', function($scope) {
$scope.ctrlTest = "Filters";
$scope.filter = {
"producers": {
"Ford": true,
"Honda": true,
"Ferrari": true
}
};
$scope.hideMe = function(key) {
$scope.filter.producers[key]=false;
$scope.checkAllproperty(); // call again to check all property
};
$scope.checkAllproperty = function() {
var allTrue = false;
for(var key in $scope.filter.producers) {
if($scope.filter.producers[key] === true){
allTrue = true;
}
}
$scope.allTrue = allTrue;
};
$scope.checkAllproperty(); // initial call when loaded
});
in html: call a hideMe function to set false
<div ng-app="myApp" ng-controller="Ctrl">
{{ctrlTest}}
<span ng-show="!allTrue">X</span>
<span ng-show="allTrue">🗸</span>
<p>
{{filter.brewers}}
</p>
<hr/>
<div>
<div>
<li ng-repeat="(key,value) in filter.producers" ng-show="value">{{key}}
<a ng-click="hideMe(key)"> X</a> // call to set this key false
</li>
</div>
{{filter.producers}}
</div>
</div>
use
Object.keys(filter.producers).length;
<span ng-show="Object.keys(filter.producers).length != 0">🗸</span>
JSBIN
you can use the JS Array.prototype.some function in your controller as follows:
$scope.flag = Object.keys($scope.filter.producers).some(
function(el) {
return $scope.filter.producers[el];
});
and in your HTML use the flag as follows:
<span ng-show="!flag">X</span>
<span ng-show="flag">🗸</span>

append html to the div with AngularJS

How can i pass html through in AngularJS controller ?
Here is my list.html:
<div class="col-xs-3" ng-repeat="item in companyData">
<a ng-click="getPackageInfo({{item.iCompanyID}},'{{item.vCompanyName}}')" class="block panel padder-v bg-primary item">
<span class="text-white block">{{item.vCompanyName}}</span>
</a>
<div id="packagehtml"></div>
</div>
<div id="lp" class="col-md-12 listing-div hidden"></div>
in controller.js:
$scope.pData = [];
$scope.getPackageInfo = function(id,name) {
$scope.name = name;
var summery = SubscriptionoptioncompanylistFactory.getSummary(id);
document.getElementById("lp").classList.remove("hidden");
$('.packages-data').html('');
$('#loading').show();
SubscriptionoptioncompanylistFactory.getPackageInDetail(id).
success(function(data) {
if(data != 0) {
$("#lp").html(summery); // this is used to append the data
document.getElementById("np").classList.add("hidden");
Array.prototype.push.apply($scope.pData, data);
$('#loading').hide();
} else {
document.getElementById("lp").classList.add("hidden");
document.getElementById("np").classList.remove("hidden");
$('#loading').hide();
}
});
};
Here, I have wrote $("#lp").html(summery);, in that div I have to append html which comes from var summery = SubscriptionoptioncompanylistFactory.getSummary(id);. But this is not going to append the data. In console I can see that data comes in summary variable. How can I do?
have a look at below modifications
Use angular ng-show for showing/hiding elements
Use data binding and avoid Jquery like Dom manipulation
<div class="col-xs-3" ng-repeat="item in companyData">
<a ng-click="getPackageInfo({{item.iCompanyID}},'{{item.vCompanyName}}')" class="block panel padder-v bg-primary item">
<span class="text-white block">{{item.vCompanyName}}</span>
</a>
<div id="packagehtml"></div>
</div>
<div id="lp" ng-show="lbVisible" class="col-md-12 listing-div hidden">{{summaryBinding}}</div>
and the controller would look like :
$scope.pData = [];
$scope.getPackageInfo = function (id, name) {
$scope.name = name;
var summery = SubscriptionoptioncompanylistFactory.getSummary(id);
$scope.lbVisible = true; //document.getElementById("lp").classList.remove("hidden");
$('.packages-data').html('');
$scope.loadingVisible = true; //$('#loading').show();
SubscriptionoptioncompanylistFactory.getPackageInDetail(id).
success(function (data) {
if (data != 0) {
$scope.summaryBinding = summery; // $("#lp").html(summery); // this is used to append the data
$scope.npVisible = false; // document.getElementById("np").classList.add("hidden");
Array.prototype.push.apply($scope.pData, data);
$scope.loadingVisible = false; // $('#loading').hide();
} else {
$scope.lbVisible = false; //document.getElementById("lp").classList.add("hidden");
$scope.npVisible = false; //document.getElementById("np").classList.remove("hidden");
$scope.loadingVisible = false; // $('#loading').hide();
}
});
};
your snippet is not showing elements that you use :
np, #loading so just find them and add the `ng-show` with the proper scope variable : `npVisible , lbVisible , loadingVisible`
and note that we add the data using summaryBinding
hope this helps :)

Form functionality lost in ng-if

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 ;-)

Angularjs Hide Show Clean coding

Hey guys I wonder if there's a solution on this mess I normally create in Angular projects:
app.controller('indexController', function ($scope) {
scope.hideWinkelContainer = true;
scope.hideWinkelPaneel = true;
scope.headerCart = false;
scope.showCart = function () {
scope.hideWinkelContainer = false;
scope.hideWinkelPaneel = false;
};
scope.hideCart = function () {
scope.hideWinkelContainer = true;
scope.hideWinkelPaneel = true;
};
});
html:
<div class="containerWinkelwagen" ng-hide="hideWinkelContainer"> <div class="winkelWagenPaneel" ng-hide="hideWinkelPaneel">
<div class="winkelWagenTerug" ng-click="hideCart()"></div>
<div class="winkelWagenTerug" ng-click="showCart()"></div>
</div>
</div>
Best practices, tips, examples are always welcome!
You can simply use a toggle function as follow:
app.controller('indexController', function ($scope) {
$scope.hideWinkelContainer = true;
$scope.hideWinkelPaneel = true;
$scope.headerCart = false;
$scope.toggleCart = function () {
$scope.hideWinkelContainer = !$scope.hideWinkelContainer;
$scope.hideWinkelPaneel = !$scope.hideWinkelPaneel;
};
});
In your HTML:
<div class="containerWinkelwagen" ng-hide="hideWinkelContainer">
<div class="winkelWagenPaneel" ng-hide="hideWinkelPaneel">
<div class="winkelWagenTerug" ng-click="toggleCart()"></div>
<div class="winkelWagenTerug" ng-click="toggleCart()"></div>
</div>
</div>
You can implement the show/hide functions once in a factory, and then inject it into the controllers that need it. Saves a lot of boilerplate.

Categories

Resources