angular js ng-show is not working - angularjs

Html code:
<div ng-controller="StoreController">
<div ng-repeat="store in gems">
{{store.name}}<br>
{{store.price}}
{{store.canPurchase}}
{{store.soldOut}}
<button ng-show="store.canPurchase">Add to Cart</button>
</div>
</div>
JS code:
myApp.controller('StoreController', ['$scope', function($scope){
$scope.gems=[
{name: 'Azurite', price: '110.50', canPurchase: 'false', soldOut: 'true'},
{name: 'Azurite +', price: '120.50', canPurchase: 'true', soldOut: 'false'}
];
}]);
I tried with ng-show="true" and ng-show="false", my code is working as expected.
I am printing store.canPurchase value on my html page and values are displayed correctly.
But when I give store.canPurchase in ng-show the code doesn't work.

remove the quotation marks and it will work fine. The false and true values of canPurchase are now strings ("") and not booleans.
$scope.gems=[
{name: 'Azurite', price: '110.50', canPurchase: false, soldOut: true},
{name: 'Azurite +', price: '120.50', canPurchase: true, soldOut: false}
];
Plunkr
The same goes for soldOut btw :)

Related

Angular ng-repeat filter to hide elements

I need filter for ng-repeat, which will hide elements.
If $scope.selected will get true, i need to hide elements when select: true or visible: false
$scope.selected = false;
$scope.array = [
{name: 'item1', select: true, visible: false},
{name: 'item2', select: true, visible: true},
{name: 'item3', select: false, visible: true},
{name: 'item4', select: true, visible: false},
{name: 'item5', select: false, visible: true},
]
<div ng-repeat="item in array">
<div>{{item.name}}</div>
</div>
In this case you need use filter.
Live example in jsfiddle.
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope) {
$scope.selected = true;
$scope.myFilter = function(item){
return $scope.selected && (!item.visible || item.select)
}
$scope.array = [
{name: 'item1', select: true, visible: false},
{name: 'item2', select: true, visible: true},
{name: 'item3', select: false, visible: true},
{name: 'item4', select: true, visible: false},
{name: 'item5', select: false, visible: true},
]
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="item in array|filter:myFilter">
<div>{{item.name}}</div>
</div>
</body>
Try this
<div ng-repeat="item in arrray">
<div ng-show="selected">
<div ng-hide="item.visible==false && item.select==true">{{item.name}}</div>
</div>
</div>
use ng-if:
<div ng-if="item.visible && selected && item.select == true">{{item.name}}</div>
I would recommend this one:
<div ng-repeat="item in array">
<div ng-hide="selected && (!item.visible || item.select)">{{item.name}}</div>
</div>

AngularJs Ng-Repeat Accessing an Array within an Array (without nested ng-repeat)

I want to access the data within an array within an array, without using nested ng-repeats because when I do this it shows the content I only want to display once multiple times. I want to make an ng-repeat that only cyles through the data in my inner most arrays, while still being aware of what outer array's data it is housed in so that it will change on the users click. Here is my code:
HTML
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="rightSection">
<form>
<div class="btn-group"> <a class="btn btn-default dropdown-toggle btn-select" data-toggle="dropdown" href="#">Submit Idea</a></div>
</form>
<div id="list2" class="list-group">
<div id="generalInfo">
<d2 id="productViewerTitle">{{productViewer.title}}</d2>
<br/>
<p id="productViewerRating" class="glyphicon glyphicon-chevron-up">{{productViewer.rating}}</p>
<p id="productViewerUsers">{{productViewer.users}}<span class="glyphicon glyphicon-user"></span></p>
<br/>
<p id="productViewerLanguage">{{productViewer.tool}}</p>
<br/>
<div id="bigImageHolder"><img id="productViewerImage" src={{productViewer.image}} alt=""/></div>
<br/>
</div>
<div id="longDescriptionSection">
<p id="productViewerDescription">{{productViewer.description}}</p>
</div>
<div id="jobListings">
<div id="jobTitle">
<p id="availableJobsTitle">Available Jobs</p>
</div>
<div>
<div id="jobsContainer" ng-repeat="product in products">
<div id="jobHolder" ng-repeat="job in product.jobs">
<p id="jobName">{{productViewer.title}}</p>
<p id="jobPay">{{job.pay}}</p>
<p id="jobDifficulty">Difficutly: {{job.difficulty}}</p>
<p id="jobCredential" class="glyphicon glyphicon-plus-sign">{{job.credential}}</p>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
JAVASCRIPT:
$(function() {
$('#signUpButton').click(function(){
$('.overlay').fadeIn('fast',function(){
$('#signUpForm').animate({'top':'160px'},500);
});
});
$('#logInButton').click(function(){
$('.overlay').fadeIn('fast',function(){
$('#logInForm').animate({'top':'160px'},500);
});
});
$('#boxCloseLogIn').click(function(){
$('.overlay').fadeOut('fast');
$('#logInForm').animate({'top':'-500px'},500,function(){
});
});
$('#boxCloseSignUp').click(function(){
$('.overlay').fadeOut('fast');
$('#signUpForm').animate({'top':'-500px'},500,function(){
});
});
});
//Dropdowns
//$(".dropdown-menu li a").click(function(){
// var selText = $(this).text();
// $(this).parents('.btn-group').find('.dropdown-toggle').html(selText+' <span class="caret"></span>');
//});
$(".dropdown-menu li a").click(function(){
$(".btn:first-child").html($(this).text()+' <span class="caret"></span>');
});
angular.module("findAProject", [])
.controller("projectFinderPage", function($scope) {
$scope.relevance = '-rating';
$scope.tools = '-tool';
$scope.topic = '-topic';
$scope.info = function(product) {
$scope.productViewer = product;
};
$scope.jobListings = function(product) {
$scope.jobViewer = product;
};
$scope.products = [
{title:'Proper Plants Website Redesign',
image:'http://www.interactive-biology.com/wp-content/uploads/2012/07/Pea-Plant11.jpg',
description:'Help redesign the layout of Proper Plants based in Kentucky!',
tool:'HTML/CSS/JAVASCRIPT',
users:321,
rating:100,
topic:"TECHNOLOGY",
jobs:[
{name: 'Backend Engineering', difficulty: 'Hard', credential: 'Knowledge of SQL backend logging', pay: '1000'},
{name: 'Object Color Correction', difficulty: 'Easy', credential: 'Ability to normalize color ranges', pay: '50'},
{name: 'AngularJs Implementation', difficulty: 'Medium', credential: 'Understanding of ngRepeat and ngSort', pay: '100'},
{name: 'Advertisement', difficulty: 'Easy', credential: 'Ability to effectively market to 100+', pay: '150'},
{name: 'Title UI Redesign', difficulty: 'Easy', credential: 'Can make a functional logo redesign', pay: '50'},
{name: 'SQL System Management', difficulty: 'Very Hard', credential: "Ability to maintain a parsed server", pay: '1500'},
{name: 'Facebook Page Management', difficulty: 'Very Easy', credentials: 'Basic social skills', pay: '25/w'},
{name: 'Competitor Market Research', difficulty: 'Medium', credentials: 'Marketing Degree', pay:'120'},
{name: "TESTING TESTING", difficulty: "Medium", credentials: "None", pay:"10"}]},
{title:'Tiper Logo Redesign', image:'http://site.xavier.edu/polt/typewriters/underwood5small.jpg', description:'Be a part of the team making the new Tiper logo!', tool:'PHOTOSHOP', users:3, rating:13, topic:"TECHNOLOGY",
jobs: [{name: 'Backend Engineering', difficulty: 'Hard', credential: 'Knowledge of SQL backend logging', pay: '1000'},
{name: 'TEST', difficulty: 'Easy', credential: 'Ability to normalize color ranges', pay: '50'},
{name: 'AngularJs Implementation', difficulty: 'Medium', credential: 'Understanding of ngRepeat and ngSort', pay: '100'},
{name: 'Advertisement', difficulty: 'Easy', credential: 'Ability to effectively market to 100+', pay: '150'},
{name: 'Title UI Redesign', difficulty: 'Easy', credential: 'Can make a functional logo redesign', pay: '50'},
{name: 'SQL System Management', difficulty: 'Very Hard', credential: "Ability to maintain a parsed server", pay: '1500'},
{name: 'Facebook Page Management', difficulty: 'Very Easy', credentials: 'Basic social skills', pay: '25/w'},
{name: 'Competitor Market Research', difficulty: 'Medium', credentials: 'Marketing Degree', pay:'120'}]},
{title:'Random Project', image:'http://i.kinja-img.com/gawker-media/image/upload/zxpvsmndjrroklechbz4.gif', description:'This is some random proejct.', tool:'C++', users:233, rating: 17},
{title:'Vent Design Logo', image:'https://m2.behance.net/rendition/pm/17643109/disp/b2b102b8772bb0cefd73e957ce73382b.png', description:'Help us with our company logo.', tool:'PHOTOSHOP', users:6, rating:34},
{title:'Neopets Reloaded', image:'http://s.hswstatic.com/gif/neopets-6.jpg', description:'Be apart of the team working on the next big thing in Neopets!', tool:'HTML/CSS/JAVASCRIPT', users:444, rating:1113},
{title:'New York Times Website', image:'http://static1.squarespace.com/static/5399cc0ae4b0705199b37aa3/5399e8a2e4b0f44ec1b1e21e/545a0216e4b05115df2de008/1429793622682/?format=1500w', description:'Help us redesign the New York Times Website', tool:'PHOTOSHOP', users:13, rating:243},
{title:'Animal Counting Algorithm', image:'http://phoenixzoo.org/wordpress/wp-content/galleries/animals-gallery-2/phoenix-zoo-animals-17.jpg', description:'We need a complex algorithm to count our animals!', tool:'C++', users:8, rating:93},
{title:'Racing Videogame (Racers 2)', image:'http://coolcarswallpaper.com/wp-content/uploads/2012/02/32-aston-martin-v12-zagato-racecar-red-white-car-1080x1920.jpg', description:'Time to buld a racing videogame for PC and Mac!', tool:'C#', users:39, rating:63},
{title:'Trash Location App', image:'http://www.ozarkalabama.org/ozark/Portals/0/trash-symbol.jpg', description:'We are making an app to help garbage men locate trash!', tool:'C#', users:5, rating:27}
];
$scope.productViewer = '';
$scope.jobViewer = '';
})
.directive("navBar", function() {
return {
restrict: "E",
templateUrl: "nav-bar.html"
};
})
.directive("titleArea", function() {
return {
restict: "E",
templateUrl: "title-area.html"
};
})
.directive("leftSide", function() {
return {
restrict: "E",
templateUrl: "left-side.html"
};
})
.directive("rightSide", function() {
return {
restrict: "E",
templateUrl: "right-side.html"
};
})
So in essence I want to make it so when I have clicked on an element of the products array I can display just the information in the jobs array of that clicked products array in an ng-repeat.

Dynamically preselected dropdowns with angular

In javascript, I have two arrays of objects and am trying to create dropdowns in the html using angular.js:
$scope.members=[
{name: "Paul", position: "Vocals"},
{name: "John", position: "Guitar"},
{name: "George", position: "Guitar"},
{name: "Ringo", position: "Drums"}
];
$scope.positions=[
{label: "Guitar"},
{label: "Vocals"},
{label: "Drums"}
];
HTML:
<select>
<option ng-repeat="position in positions">
{{member.position}}
</option>
</select>
The current HTML is taking the member's position and duplicating it 3 times as the only option in the dropdown. For example, upon loading the page, Ringo's position is preselected as "drums" in the dropdown (that's the way it should be). But when clicking on the dropdown,the options for Ringo are "drums" and "drums", and "drums". They should be "drums", "vocals", and "guitar".
Is there a way to have all the options available AND have the correct one preselected on loading? What's the proper directive?
AngularJS has a directive specifically for select controls. Use it instead of ng-repeat
https://docs.angularjs.org/api/ng/directive/ngOptions
working plunkr
var app = angular.module('plunker', []);
app.controller("MyCtrl", function ($scope) {
$scope.members = [
{name: "Paul", position: "Vocals", alive: true},
{name: "John", position: "Guitar", alive: false},
{name: "George", position: "Guitar", alive: false},
{name: "Ringo", position: "Drums", alive: true}
];
$scope.positions = [
{label: "Guitar"},
{label: "Vocals"},
{label: "Drums"}
];
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<script data-require="angular.js#1.3.x" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="MyCtrl">
<ul>
<li ng-repeat="member in members">
{{member.name}}
<select ng-options="position.label as position.label for position in positions" ng-model="member.position"></select>
<input type="checkbox" ng-model="member.alive">Alive?</input>
</li>
</ul>
<pre>
{{members | json}}
</pre>
</div>
</body>
</html>
<select ng-model="selectedBeetle" ng-options="member as member.name for member in members"></select>
<select ng-model="selectedBeetle.position" ng-options="position.label for position in positions"></select>

angularjs filter on nested objects

I am quite new with angularjs so I am not sure if what I am trying to do is the right way. Basically I want to display in my page a nested object, and a filter, this way the user can easily type keywords on an input and the content get filtered, to only display the recods that get found by the filter
However I notice that the filter gets the whole parent object and i was expecting only display the record, so with the following code, if i search for Japan it will display Sydney, Melbourne and los angeles.
Javascript
<script type="text/javascript">
var demoApp = angular.module('demoApp',['ngSanitize']);
demoApp.controller('simpleC',['$scope', function ($scope){
$scope.info = [
{name: 'Documents',links: [
{linkname:'title1',linknamesublink:[
{namesublink:'document 1', description: 'Sydney'},
{namesublink:'document 2', description: 'Tokyo <b>Japan</b>'}
]},
{linkname:'title2',linknamesublink:[
{namesublink:'document 3', description: 'Melbourne'},
{namesublink:'document 4', description: 'Los Angeles'}
]}
]},
{name: 'Video',links: [
{linkname:'title1',linknamesublink:[
{namesublink:'video 1', description: 'California'},
{namesublink:'video 2', description: 'San Francisco <b> USA</b>'}
]},
{linkname:'title2',linknamesublink:[
{namesublink:'video 3', description: 'South America'},
{namesublink:'video 4', description: 'Northern <b>Europe</b>'}
]},
{linkname:'title3',linknamesublink:[
{namesublink:'video name 5', description: 'Africa'},
{namesublink:'video name 6', description: 'Bangkok <b>Thailand</b>'}
]}
]},
];
}]);
</script>
html:
<div class="container" ng-app="demoApp">
<br /><input type="text" class="form-control" ng-model="search" >
<div ng-controller="simpleC">
<div ng-repeat="i in info | filter:search" >
{{i.name}} :
<div ng-repeat="link in i.links">
{{link.linkname}}
<div ng-repeat="sublink in link.linknamesublink">
{{sublink.namesublink}}: <!--{{sublink.description}}-->
<span ng-bind-html="sublink.description"></span>
</div>
</div>
</div>
</div>
</div>
Follow this example
http://www.whatibroke.com/?p=857
You can use filter in ng-repeat to filter items by property or write a filter yourself.
The author want to filter postcode property by the value of searc_postcode. So, he wrote //filter {postcode : search_postcode} //
Ps. Sorry, I misinterpret your question.
Write your own filter function. This way, you have total control over what is returned. https://docs.angularjs.org/api/ng/filter/filter
module.filter('searchfilter', function() {
return function(searchexpr) {
var filteredList = ['my', 'filtered', 'result'];//implement yourself
return filteredList;
};
});
and use searchfilter instead of filter in your markup.
Or, try to use a filter function as described here: http://fdietz.github.io/recipes-with-angular-js/common-user-interface-patterns/filtering-and-sorting-a-list.html (as far as I can tell, you didn't define a search function, i.e. the first agument for the filter expression).
Modified :
If you want to filter the objects based on any field(say "name"), you can use the below format
<div ng-repeat="i in info" ng-if="search==i.name">

How to separate groups in ng-repeat

I have items I want to show, normally by using ng-repeat. I want to show the in some order (easy), but whenever the ordered attribute changes, I want some HTML in-between.
Example: (Fiddle):
<div ng-app ng-controller="Main">
<div ng-repeat="item in items | orderBy:'role'">
{{item.role}} - {{item.name}}
</div>
</div>
function Main($scope){
$scope.items = [{name: 'First', role: 1},
{name: 'Second', role:2},
{name: 'Third', role: 1},
{name: 'Fourth', role: 2}];
}
I want it to print:
1 - First
1 - Third
(some separator kode)
2 - Second
2 - Fourth
You will want to create a function in your scope.
$scope.currentRole = 'something';
$scope.CreateHeader = function(role) {
showHeader = (role!=$scope.currentRole);
$scope.currentRole = role;
return showHeader;
}
And then in your HTML:
<div ng-app ng-controller="Main">
<div ng-repeat="item in items | orderBy:'role'">
<div ng-show="CreateHeader(item.role)">
something here for the header
</div>
{{item.role}} - {{item.name}}
</div>
</div>
The solution by #lucuma only works on the first time through the loop. If Angular refreshes the list, the variable will still be set from the previous loop.
Instead, I added a new attribute to the list (say, header) during initialization:
function Main($scope){
$scope.items = [{name: 'First', role: 1, header: false},
{name: 'Second', role:2, header: false},
{name: 'Third', role: 1, header: true},
{name: 'Fourth', role: 2, header: false}];
}
Then the HTML by #lucuma works:
<div ng-app ng-controller="Main">
<div ng-repeat="item in items | orderBy:'role'">
<div ng-show="item.header"> // <== with this change
something here for the header
</div>
{{item.role}} - {{item.name}}
</div>
</div>
Oh, and you could sort the list once at initialization and remove the orderBy filter.

Resources