Compare a specific object value and do something if - javascript

Just started to learn Angular and I am facing an issue as described below:
Given the following scenario:
var app = angular.module('test', []);
app.controller('MainController', ['$scope',
function($scope) {
$scope.title = 'This is another test';
$scope.promo = 'More or less'
$scope.products = [{
name: 'Product 1',
price: 19,
stock: 20
}, {
name: 'Product 2',
price: 19,
stock: 12
}, {
name: 'Product 3',
price: 19,
stock: 3
}, {
name: 'Product 4',
price: 19,
stock: 0
}, ]
}
]);
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
</head>
<style>
.stock {
color: green;
}
.zeroStock {
color: red;
}
.buy {
background-color: green;
color: #fff;
margin-bottom: 20px;
border: 0;
padding: 10px 20px;
}
.outOfStock {
background-color: red;
}
</style>
<body ng-app="test">
<div class="main" ng-controller="MainController">
<div class="test" ng-repeat="product in products">
<div class="name"> {{product.name}} </div>
<div class="price"> {{product.price}} </div>
<div id="stock" class="stock"> {{product.stock}} </div>
<button class="buy">BUY</button>
</div>
</div>
<script src="js/app.js"></script>
<script src="js/controllers/MainController.js"></script>
</body>
</html>
What I'd like to achieve is:
Create a function or directive which will compare each stock quantity
if stock = 0:
button get class: "outOfStock"
button copy will change from "BUY" to "OUT OF STOCK"
stock copy will get the class: "zeroStock"
My apologies if this might sounds silly or if might be a duplicate question, I did try to look for it, but I have potentially used the wrong terminology.
Thank you for your help.

You can use ng-class and ng-if for this, there is even no need for any function:
Example:
var app = angular.module('test', []);
app.controller('MainController', ['$scope',
function($scope) {
$scope.title = 'This is another test';
$scope.promo = 'More or less'
$scope.products = [{
name: 'Product 1',
price: 19,
stock: 20
}, {
name: 'Product 2',
price: 19,
stock: 12
}, {
name: 'Product 3',
price: 19,
stock: 3
}, {
name: 'Product 4',
price: 19,
stock: 0
}, ]
}
]);
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
</head>
<style>
.stock {
color: green;
}
.zeroStock {
color: red;
}
.buy {
background-color: green;
color: #fff;
margin-bottom: 20px;
border: 0;
padding: 10px 20px;
}
.outOfStock {
background-color: red;
}
</style>
<body ng-app="test">
<div class="main" ng-controller="MainController">
<div class="test" ng-repeat="product in products">
<div class="name"> {{product.name}} </div>
<div class="price"> {{product.price}} </div>
<div id="stock" class="stock" ng-class="{'zeroStock': product.stock == 0}"> {{product.stock}} </div>
<button class="buy" ng-if="product.stock != 0">BUY</button>
<button ng-if="product.stock == 0" class="outOfStock">Out Of stock</button>
</div>
</div>
<script src="js/app.js"></script>
<script src="js/controllers/MainController.js"></script>
</body>
</html>

Related

Vue js task if statement

Hello, I have a little task in vue js and have a little problem, I need If statement which makes ul border color green if price < 140. I need help, thank you.I tried some ways but didn't work.
See the code below:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue</title>
<link rel="stylesheet" href="style.css">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<style>
ul{
border:2px solid black;
width:450px;
}
#app{
display: flex;
justify-content: center;
}
#card{
margin-left:5px;
}
</style>
<body>
<div id = "app" >
<div id ="card" v-for="post in posts" >
<ul>
<img :src="post.img" :value="post.id">
<li>{{post.title}}</li>
<li>{{post.price}}</li>
<li>{{post.date}}</li>
</ul>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
var card = new Vue({
el: '#app',
data: {
posts: [
{ id: 1, title: 'Cat', price: 145, date: "1 year ago", img: 'https://www.pngonly.com/wp-content/uploads/2017/06/Cat-Clipart-PNG-Image.png' },
{ id: 2, title: 'Cat2', price: 80, date: "2 years ago", img: 'https://www.pngonly.com/wp-content/uploads/2017/06/Cat-Clipart-PNG-Image.png' },
{ id: 3, title: 'Cat3', price: 180, date: "3 years ago", img: 'https://www.pngonly.com/wp-content/uploads/2017/06/Cat-Clipart-PNG-Image.png' }
],
baseStyles: {
borderColor:'green',
},
}
})
Solved
You can achieve it with the ternary operator
<ul :style="{ 'border-color': post.price < 140 ? 'green' : '' }">
<img :src="post.img" :value="post.id">
<li>{{post.title}}</li>
<li>{{post.price}}</li>
<li>{{post.date}}</li>
</ul>

Kendo UI Menu items select issue

Issue: Clicking on the image in the kendo menu item, the select event is not triggering.
what i have tried: See the sample code below
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/menu/images">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.1.118/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.1.118/styles/kendo.material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.1.118/styles/kendo.material.mobile.min.css" />
<script src="https://kendo.cdn.telerik.com/2017.1.118/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.1.118/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example">
<div class="demo-section k-content">
<h4>Menu with images</h4>
<ul id="menu-images"></ul>
</div>
<script>
$("#menu-images").kendoMenu({
dataSource: [
{
text: "Golf", imageUrl: "../content/shared/icons/sports/golf.png",
items: [
{
text: "Top News",
imageUrl: "../content/shared/icons/16/star.png",
select: function (e) {
alert('Clicking on image select event is not triggering')
}
},
{ text: "Photo Galleries", imageUrl: "../content/shared/icons/16/photo.png" },
{ text: "Videos Records", imageUrl: "../content/shared/icons/16/video.png" },
{ text: "Radio Records", imageUrl: "../content/shared/icons/16/speaker.png" }]
},]
});
</script>
<style>
#menu-sprites .k-sprite {
background-image: url("../content/shared/styles/flags.png");
}
.brazilFlag {
background-position: 0 0;
}
.indiaFlag {
background-position: 0 -32px;
}
.netherlandsFlag {
background-position: 0 -64px;
}
.historyIcon {
background-position: 0 -96px;
}
.geographyIcon {
background-position: 0 -128px;
}
</style>
</div>
</body>
</html>
Description:
I have edited this code sample taken from Telerik demo. in the above code i have added the items for Golf. that also have the select function which is what i am talking about. after executing this. If i click on the text "Top News" the alert will trigger.The alert is not working when i click/select on the image.
Posting in Telerik forum is only applicable for licensed users. I dont have.
Let me know if any body come across these kind of issue.
Thanks
Dev
It seems like you have nested the event-declaration within the dataSource-item.
Just move the declaration to the menu-level and it should work.
$("#menu-images").kendoMenu({
select: function(e) {
alert($(e.item).children('.k-link').text())
}
dataSource: [
{
text: "Golf", imageUrl: "../content/shared/icons/sports/golf.png",
items: [
{
text: "Top News",
imageUrl: "../content/shared/icons/16/star.png"
},
{ text: "Photo Galleries", imageUrl: "../content/shared/icons/16/photo.png" },
{ text: "Videos Records", imageUrl: "../content/shared/icons/16/video.png" },
{ text: "Radio Records", imageUrl: "../content/shared/icons/16/speaker.png" }]
},]
});
Using $(e.item) you can go further and figure out which item has been selected. Have a look the event-section of the online-demo. http://demos.telerik.com/kendo-ui/menu/events

Animation in react-dnd

In this Angular example, if you drag an apple to the orange section and drop it there, then there is an animation which slowly returns the apple to the spot it came from. This visually communicates that dragging an apple to the orange section is not valid. The Angular drag and drop library used is from codef0rmer.
How would I create a similar animation in react-dnd or another react drag and drop package?
Here is a React drag and drop example with some animation. Can I do something like this with react-dnd, or another widely used package?
The rest is the Angular sample code which is also in plnkr Angular example.
index.html:
<!DOCTYPE html>
<html ng-app="drag-and-drop">
<head lang="en">
<meta charset="utf-8">
<title>Drag & Drop: Multiple listsr</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/ui-lightness/jquery-ui.min.css" rel="stylesheet" type="text/css" />
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="angular-dragdrop.min.js"></script>
<script src="app.js"></script>
<style>
.thumbnail {
height: 280px !important;
}
.btn-droppable {
width: 180px;
height: 30px;
padding-left: 4px;
}
.btn-draggable {
width: 160px;
}
</style>
</head>
<body>
<div ng-controller="oneCtrl">
<!-- Drag Apple -->
<div>
<div class="btn"
ng-repeat="item in applesin"
data-drag=true
data-jqyoui-options="{revert: 'invalid'}"
ng-model="applesin"
jqyoui-draggable="{index: {{$index}}, placeholder:'keep', animate:true}"
>
{{item.title}}
</div>
</div>
<!-- Drop Apple -->
<div>
<div class="thumbnail"
data-drop="true"
ng-model="applesout"
data-jqyoui-options="appleOptions"
data-jqyoui-droppable="{onDrop: 'appleOnDrop'}"
>
<div
ng-hide=applesout.title
ng-model="applesout"
>
Drop an apple here
</div>
<div
class="btn"
ng-hide=!applesout.title
ng-model="applesout"
>
{{applesout.title}}
</div>
</div>
</div>
<!-- Drag Orange -->
<div>
<div class="btn"
ng-model="orangesin"
ng-repeat="item in orangesin"
data-drag="true"
data-jqyoui-options="{
revert: 'invalid',
scroll: 'true',
containment: 'body',
helper: 'clone',
appendTo: 'body'
}"
jqyoui-draggable="{index: {{$index}}, placeholder:'keep', animate:true}"
>
{{item.title}}
</div>
</div>
<!-- Drop Orange-->
<div>
<div class="thumbnail"
data-drop="true"
ng-model="orangesout"
data-jqyoui-options="validateDropOranges"
jqyoui-droppable="{multiple:false}">
<div
ng-hide=orangesout.title
ng-model="orangesout"
>
Drop an orange here
</div>
<div
class="btn"
ng-hide=!orangesout.title
ng-model="orangesout"
>
{{orangesout.title}}
</div>
</div>
</div>
</div>
</body>
</html>
And app.js:
varApp = angular.module('drag-and-drop', ['ngDragDrop']);
App.controller('oneCtrl',function($scope, $timeout) {
$scope.applesin = [
{ 'title': 'Apple 1'},
{ 'title': 'Apple 2'},
{ 'title': 'Apple 3'},
{ 'title': 'Apple 4'}
];
$scope.applesout = {};
$scope.orangesin = [
{ 'title': 'Orange 1'},
{ 'title': 'Orange 2'},
{ 'title': 'Orange 3'},
{ 'title': 'Orange 4'}
];
$scope.orangesout = {};
$scope.appleOnDrop = function(e, obj) {
console.log("on drop apple ");
console.log("$(e.target).scope(): ");
console.log($(e.target).scope());
var dest = $(e.target).scope().this;
console.log("$(obj.draggable).scope(): ");
console.log($(obj.draggable).scope());
var src = $(obj.draggable).scope().x;
};
// Limit apples to apples, oranges to oranges
$scope.appleOptions = {
accept: function(dragEl) {
console.log("validate apple");
if (dragEl[0].innerHTML.indexOf("Apple") > -1) {
return true;
} else {
return false;
}
}
};
$scope.validateDropOranges = {
accept: function(dragEl) {
console.log("validate orange");
if (dragEl[0].innerHTML.indexOf("Orange") > -1) {
return true;
} else {
return false;
}
}
};
});
Yes, you can use React DnD (https://github.com/react-dnd/react-dnd) for the actual drag and drop functionality and React Flip Move (https://github.com/joshwcomeau/react-flip-move) or React Motion (https://github.com/chenglou/react-motion) for animating the DOM changes.
They all have enough simple examples/tutorials to get you going..

How to set border style for img element in AngularJS

This is a beginners question in AngularJS.
I'm writing a simple application to show a few images and allow the user to toggle selection. Only one image should be selected at any one time.
Anyway, how to set the style to change the border for the img tag. When the user clicks on an image the style should be set. Neither setting the style or custom style myStyle is working (style not applied).
<!DOCTYPE html>
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script >
function myCtrl($scope, $window) {
$scope.vm = {};
$scope.vm.Courses = [
{ Id: 1, Name: "Course 1"},
{ Id: 2, Name: "Course 2"}
];
$scope.ToggleCourse = function(imageElement) {
console.log("id = " + imageElement.id);
imageElement.style = "{border:'2px solid blue'}"; // doesnt work
imageElement.myStyle = "{border:'2px solid blue'}"; // neither does this///
}
}
</script>
</head>
<body ng-controller="myCtrl">
<div>
<div ng-repeat="course in vm.Courses">
<div>
<div ng-click="ToggleCourse($event.target)">
<label>{{course.Name}}</label>
<img id="card{{course.Id}}" src="course.png" ng-style="myStyle">
</div>
</div>
</div>
</div>
</body>
</html>
You are doing it wrong. Don't use DOM manipulations at all. Just forget about this possibility until you understand why. Instead use ngClass directives (also don't use ngStyle):
<!DOCTYPE html>
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script >
function myCtrl($scope, $window) {
$scope.vm = {};
$scope.vm.Courses = [
{ Id: 1, Name: "Course 1"},
{ Id: 2, Name: "Course 2"}
];
$scope.ToggleCourse = function(course) {
$scope.selected = course;
}
}
</script>
<style>
.selected img {border: 2px solid blue;}
</style>
</head>
<body ng-controller="myCtrl">
<div>
<div ng-repeat="course in vm.Courses">
<div>
<div ng-click="ToggleCourse(course)" ng-class="{selected: course === selected}">
<label>{{course.Name}}</label>
<img id="card{{course.Id}}" src="course.png" ng-style="myStyle">
</div>
</div>
</div>
</div>
</body>
</html>
Replace the ng-style="myStyle" with:
ng-class="myStyle"
And define the class in CSS:
.myStyle {border: 2px solid #999;}
The above is the cleaner method as it just sets the necessary class for the <img /> element and you can style it, so that the presentation and styles are separated. You can also use the $scope and define a function and inject the styles.

Angular Ui grid Coloumndefs bug

When i am using the following code, this is working fine
<!doctype html>
<html ng-app="app">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
<script src="ht tp://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-touch.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-animate.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/csv.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/pdfmake.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/vfs_fonts.js"></script>
<script src="http://ui-grid.info/release/ui-grid-unstable.js"></script>
<link rel="stylesheet" href="http://ui-grid.info/release/ui-grid-unstable.css" type="text/css">
<link rel="stylesheet" href="main.css" type="text/css">
</head>
<body>
<div ng-controller="MainCtrl">
<br>
<br>
<div id="grid1" ui-grid="gridOptions" class="grid"></div>
</div>
<style type="text/css">
.grid {
width: 500px;
height: 200px;
}
.red { color: red; background-color: yellow !important; }
.blue { color: blue; }
</style>
<script>
var app = angular.module('app', ['ui.grid']);
app.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.gridOptions = {
enableSorting: true,
columnDefs: [
{ field: 'name', cellClass: 'red' },
{ field: 'company',
cellClass: function (grid, row, col, rowRenderIndex, colRenderIndex) {
if (grid.getCellValue(row, col) === 'Velity') {
return 'blue';
}
}
}
];
};
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/100.json')
.success(function (data) {
$scope.gridOptions.data = data;
});
} ]);
</script>
</body>
</html>
When I was using Columndefs as a variable, this is not working?
Is this a bug in angular ui grid
<!doctype html>
<html ng-app="app">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-touch.js"> </script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-animate.js"> </script>
<script src="http://ui-grid.info/docs/grunt-scripts/csv.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/pdfmake.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/vfs_fonts.js"></script>
<script src="http://ui-grid.info/release/ui-grid-unstable.js"></script>
<link rel="stylesheet" href="http://ui-grid.info/release/ui-grid-unstable.css" type="text/css">
<link rel="stylesheet" href="main.css" type="text/css">
</head>
<body>
<div ng-controller="MainCtrl">
<br>
<br>
<div id="grid1" ui-grid="gridOptions" class="grid"></div>
</div>
<style type="text/css">
.grid {
width: 500px;
height: 200px;
}
.red { color: red; background-color: yellow !important; }
.blue { color: blue; }
</style>
<script> var app = angular.module('app', ['ui.grid']);
app.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.cv = [
{ field: 'name', cellClass: 'red' },
{ field: 'company',
cellClass: function (grid, row, col, rowRenderIndex, colRenderIndex) {
if (grid.getCellValue(row, col) === 'Velity') {
return 'blue';
}
}
}
];
$scope.gridOptions = {
enableSorting: true,
columnDefs: 'cv'
};
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/100.json')
.success(function (data) {
$scope.gridOptions.data = data;
});
} ]);
</script>
</body>
</html>
Guys if you know, then please help me
I was making a dynamic templates using angular ui grid, And I got this type of silly error very soon.
I was thinking that adding dynamic validation in angular grid fields would be the challenging task, but i never thought that i will get this type of error.
The columnDefs option no longer accepts a string as an argument. It's not well-documented but it's mentioned in the upgrade guide: http://ui-grid.info/docs/#/tutorial/099_upgrading_from_2#updatecolumndefs
You can assign either a named or anonymous array:
$scope.myColDefs = [...];
$scope.gridOptions.columnDefs = $scope.myColDefs;
// or:
$scope.gridOptions.columnDefs = [...];

Categories

Resources