Angular Injector error trying to use angular-gridify - javascript

Got a jsFiddle here
I'm trying to use angular-gridify in a similar way to this, but I am getting an $injector error as below. How should I be injecting the angular-gridify dependency, assuming that's what the problem is?
Uncaught Error: [$injector:modulerr] Failed to instantiate module testApp due to:
Error: [$injector:nomod] Module 'testApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
HTML:
<body ng-app="ExampleApp" ng-controller="ExampleCtrl" ng-click="generateTiles()">
<div class="gridify" ng-gridify="{wrapperSelector: '.wrapper', tileSelector: '.tile', perRow: 5, averageRatio: 1.5, gutter: 10, watch: 'tiles'}">
<div class="wrapper">
<div ng-repeat="tile in tiles" class="tile" data-ratio="{{tile.ratio}}" style="background-color: {{tile.color}}">
<img src="{{tile.src}}"></img>
</div>
</div>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script>
<script type="text/javascript" src="angular-gridify.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
JavaScript:
var testApp = angular.module('testApp', ['ngRoute', 'angular-gridify']).config(function() {});
testApp.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/', {
controller: 'testCtrl'
})
});
testApp.controller('testCtrl', function($scope) {
$scope.tiles = [];
$scope.generateTiles = function() {
for (var i = 0; i < 50; i++) {
var ratio = Math.random() > 0.6 ? 0.661 : 1.511;
$scope.tiles[i] = {
ratio: ratio,
color: '#' + ('000000' + Math.floor(Math.random() * 16777215).toString(16)).slice(-6)
};
}
};
$scope.generateTiles();
});

In your js you registered testCtrl controller instead of ExampleCtrl controller

I too have sometimes difficulties to get an Angular app running with JSFiddle. I took your code, modified it a little and put it in Codepen:
http://codepen.io/cgav/pen/QjweXe?editors=111
JS:
var testApp = angular.module('testApp', ['ngRoute', 'angular-gridify']);
testApp.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/', {
controller: 'testCtrl'
})
});
testApp.controller('testCtrl', function($scope) {
$scope.tiles = [];
$scope.generateTiles = function() {
for (var i = 0; i < 50; i++) {
var ratio = Math.random() > 0.6 ? 0.661 : 1.511;
$scope.tiles[i] = {
ratio: ratio,
color: '#' + ('000000' + Math.floor(Math.random() * 16777215).toString(16)).slice(-6)
};
}
};
$scope.generateTiles();
});
HTML:
<div ng-app="testApp" ng-controller="testCtrl">
<div class="gridify" ng-gridify="{wrapperSelector: '.wrapper', tileSelector: '.tile', perRow: 5, averageRatio: 1.5, gutter: 10, watch: 'tiles'}">
<div class="wrapper">
<div ng-repeat="tile in tiles" class="tile" data-ratio="{{tile.ratio}}" style="background-color: {{tile.color}}">
</div>
</div>
</div>
</div>
CSS:
body {
margin: 0;
padding: 10px;
}
.tile {
width: 32px;
height: 32px;
}
.tile > img {
width: 100%;
height: 100%;
}
Is this what you are looking for?
EDIT:
Keep in mind to include the references to angular-gridify and angular-route.

Related

Reinitialize jssor slider

I am using angular js with jssor slider as follow.
As far as I am concern, there is no $destroy method for jssor slider yet. But I need the user to click on the refresh button and reinit the jssor slider.
As you can see, currently it won't work if i reinit the jssor slider by clicking the refresh function.
I do not want to call .remove() function and bind back the html as it seems to be less angular way. Is there any other method?
I can't create own $destroy method as the jssor slider library source code is uglify.
angular.module('app', [])
.controller('FrameController', ['$scope', '$injector', function($scope, $injector) {
initSlider();
$scope.refresh = initSlider;
function initSlider() {
var image = [];
var count = Math.floor(Math.random() * 6) + 1;
for (var i = 0; i < count; i++) {
image.push('https://unsplash.it/600/' + i * 100 + '?random');
}
$scope.image = image;
console.log($scope.image);
function jssor_slider1_init(containerId) {
var options = {
$AutoPlay: 1
};
var jssor_slider1 = new $JssorSlider$(containerId, options);
};
setTimeout(function() {
jssor_slider1_init('slider1_container');
});
}
}]);
setTimeout(function() {
angular.bootstrap(document.getElementById('body'), ['app']);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jssor-slider/25.2.0/jssor.slider.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<div id="body">
<div ng-controller="FrameController">
<button ng-click="refresh()">
Click to refresh
</button>
<div id="slider1_container" style="position: relative; top: 0px; left: 0px; width: 600px; height: 300px;">
<!-- Slides Container -->
<div u="slides" style="cursor: move; position: absolute; overflow: hidden; left: 0px; top: 0px; width: 600px; height: 300px;">
<div ng-repeat="item in image track by $index">
<img ng-src="{{item}}" /></div>
</div>
</div>
</div>

Problems with calling a function in the HTML file using Angular JS

I am fairly new with AngularJS. I'm trying to do something simple for the moment. I created a table with some text I'll have to search with, a reset button (In my program is called "Pulisci") and some panels I'll have to use later. The problem is that, if I call the function I created for resetting the page, the panels mysteriously stop working. I'm banging my head on this since last week.
HTML
<!DOCTYPE html>
<html ng-app="sbi">
<head>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<style>
table,
td {
border-width: 2px;
border-collapse: collapse;
padding: 15px;
color: #000000;
text-align: center;
}
table.pos_fixed1 {
position: relative;
top: 30px;
left: 10px;
}
</style>
</head>
<body>
<form name="form">
<table summary="" width="10%" class="pos_fixed1" align="center">
<tr>
<td>Code Subinstaller<br><input name="codeSub" type="text" ng-model="codeSub"></td>
<td>Stato<br>
<select>
<option value="1">...</option>
<option value="2">WHITE LIST</option>
<option value="3">GRAY LIST</option>
</select>
</td>
</tr>
<tr>
<td>Nome Sub Installer<input name="nomeSub" type="text" ng-model="nomeSub"></td>
<td>Cognome Sub Installer<input name="cognSub" type="text" ng-model="cognSub"></td>
<td>Codice Fiscale<input name="codFisc" type="text" ng- model="codFisc"> </td>
</tr>
</table><br>
<button class="btn btn-wide btn-default.active.focus" data-ng- click="">Cerca</button>
<button class="btn btn-wide btn-default.active.focus" data-ng- click="reset()">Pulisci</button>
</form><br><br>
<section ng-controller="PanelController as panel">
<ul class="nav nav-pills">
<li ng-class="{ active:panel.isSelected(1) }"> <a href ng- click="panel.selectTab(1)">Description</a></li>
<li ng-class="{ active:panel.isSelected(2) }"> <a href ng- click="panel.selectTab(2)">Specifications</a></li>
<li ng-class="{ active:panel.isSelected(3) }"> <a href ng- click="panel.selectTab(3)">Reviews</a></li>
</ul>
<div class="panel" ng-show="panel.isSelected(1)">
<h4>Description </h4>
<p>wtf</p>
</div>
<div class="panel" ng-show="panel.isSelected(2)">
<h4>Idk</h4>
<p>Idc</p>
</div>
<div class="panel" ng-show="panel.isSelected(3)">
<h4>APPARI</h4>
<p>???</p>
</div>
</section>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="myapp.js"></script>
</body>
</html>
JS
(function() {
var app = angular.module('sbi', []);
app.controller('PanelController', function() {
this.tab = 1;
this.selectTab = function(setTab) {
this.tab = setTab;
};
this.isSelected = function(checkTab) {
return this.tab === checkTab;
};
});
})();
(function($scope) {
var app = angular.module('sbi', []);
function MyCtrl($scope) {
$scope.reset = function() {
$scope.requiredField = '';
};
};
});
How can I make the Reset() and the panels work simultaneously?
You have re-initialized your angular module.
Initializing your angular module
var app = angular.module('sbi', []);
Second argument in angular.module() is for injecting the required dependency for the module. And hence should be done only once.
In your code, you have again initialized your module.
(function () {
//initialization
var app = angular.module('sbi', []);
app.controller('PanelController', function () {
this.tab = 1;
this.selectTab = function (setTab) {
this.tab = setTab;
};
this.isSelected = function (checkTab) {
return this.tab === checkTab;
};
});
})();
(function ($scope) {
//edit in your code
//re-using the already initialized module
var app = angular.module('sbi');
function MyCtrl($scope) {
$scope.reset = function () {
$scope.requiredField = '';
};
};
});
You should not pass the second argument as parameter.
Reusing your angular module
var app = angular.module('sbi');
EDIT :
Try the following code :
(function () {
var app = angular.module('sbi', []);
app.controller('PanelController', ['$scope', function($scope) {
$scope.tab = 1;
$scope.selectTab = function (setTab) {
$scope.tab = setTab;
};
$scope.isSelected = function (checkTab) {
return $scope.tab === checkTab;
};
$scope.reset = function () {
$scope.requiredField = '';
};
}]);
})();
There is something you are clearly missing here: your reset function is attached to... nothing.
The MyCtrl function is never called (from what we've seen), and the $scope variable is not injected the Angular-way. Actually, nothing here is in the Angular way. Let me try to adjust this so you understand what you should aim for.
First of all, as #Akshay mentioned, there is a huge difference between angular.module('something', []) and angular.module('something'), but they already pointed that out in their response.
Then, your MyCtrl hasn't been registered as a controller in Angular. You just defined the function, you were missing these lines:
var app = angular.module('sbi');
function MyCtrl($scope) {
$scope.reset = function () {
$scope.requiredField = '';
};
};
// This controller will be known as 'MyCtrl'
app.controller('MyCtrl', MyCtrl);
This should work. Note that you won't be needing the surrounding (function ($scope) {...}) as it won't be executed correctly.
Then, you will have to tell Angular to use that controller in that specific part of your page:
<!-- Adding the ng-controller directive here -->
<form name="form" ng-controller="MyCtrl">
...
<button class="btn btn-wide btn-default.active.focus" data-ng-click="reset()">Pulisci</button>
</form>
Then, you will be able to handle your requiredField variable as you wish.

Change background color from input

I'm using angular. I have a input that looks like:
<input class="form-control" type="text" ng-model="newBook.color">
basically when this is changed, I want a div's background color to be changed.
My controller has some lines that look like:
$scope.newBook = {};
$scope.newBook.color = "";
$scope.color = ->
return "background-color: " + $scope.newBook.color;
and then the div I want to change:
<div ng-style="{{color()}}"></div>
However, I get the error: Error: [$parse:syntax] Syntax Error: Token ':' is an unexpected token at column 17 of the expression [background-color:]
I made an example for you here: https://jsfiddle.net/chelogui/2h3hrj1x/
HTML:
<div ng-app="appTest">
<div ng-controller="contr as controller">
<input class="form-control" type="text" ng-model="controller.color" />
<div id="divTest" style="background-color: {{ controller.color }}"></div>
</div>
</div>
Javascript:
angular.module('appTest', [])
.controller('contr', [function () {
var self = this;
self.color = "red";
}]);
Css to exemple:
#divTest {
width: 100px;
height: 100px;
border: 1px solid black;
margin-top: 10px;
}
Here is a working example:
You need to change your color function to do this:
angular.module('myApp',[])
.controller('myFirst',['$scope',function($scope){
$scope.newBook = {};
$scope.newBook.color = "red";
$scope.color = function(){
return "{'background-color' : '"+$scope.newBook.color+"'}";
}
}])
Check this:
angular.module('myApp',[])
.controller('myFirst',['$scope',function($scope){
$scope.newBook = {};
$scope.newBook.color = "red";
$scope.color = function(){
return "{'background-color' : '"+$scope.newBook.color+"'}";
}
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myFirst" ng-style="{{color()}}">Ajay</div></div>

Issue with multiple child HTML elements using Directives in AngularJS

I'm using a template to create a popup menu that will show alerts if there is a new one and it's working till now. But i wanted to add manual alert, that's why i thought to add an input text but Oupss, i can't write on the input field and i don't even know why.The input field is sort of Disabled!!!
My directive is like so :
$scope.tb = { x: 0, y: 0 };
module.directive('myDraggable', function ($document, $interval) {
return {
restrict: 'EA',
replace: true,
//scope : true,
scope: { menu: '=drSrc'},
link: function (scope, element, attr) {
var startX = 0, startY = 0, x = scope.menu.x || 0, y = scope.menu.y || 0, positionX = [], positionY = [], time = [], width, height, moveInterval;
element.draggable({
position: 'relative',
cursor: 'pointer',
top: y + 'px',
left: x + 'px'
});
element.on('mousedown', function (event) {
// Prevent default dragging of selected content
event.preventDefault();
startX = event.pageX - x;
startY = event.pageY - y;
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
$interval.cancel(moveInterval);
});
function mousemove(event) {
y = event.pageY - startY;
x = event.pageX - startX;
//calculate the borders of the document
width = $(document).width() - 350;
height = $(document).height() - 150;
positionX.push(x);
positionY.push(y);
time.push(Date.now());
}
}
}
});
I tried to make scope true but i faced 2 problems, :
I can't move my popup anymore (yes my popup menu is Draggable)
And Also the input text does not show my text i'm typing.
Here's my cache template :
$templateCache.put('control.tpl.html', '<div class="container" my-draggable dr-src="tb"><div><div class="col-sm-1 col-md-1 sidebar"><div class="list-group" ><span href="#" class="list-group-item active" >Manage<input type="text" class="pull-right" placeholder="Type..." /></span><div ng-repeat="Alert in Alerts"><a href="#" ng-click="showLocation(Alert.id)" class="list-group-item" >Alert {{Alert.id}}</span><img src="../images/alert_icon_manage.png" class="pull-right"/> </a></div><span href="#" class="list-group-item active"></span></div></div></div></div>');
I'm new with AngularJS and Directive and I don't know how to solve this but I think it's a problem with Scopes!!
Thank you.
UPDATE :
If I delete scope:{menu:"=drSrc"} That work and i can type what i want but the problem is that my element is no more draggable.
I think it's sth related to scopes. can anyone help please?
scope: true indicates that your directive should inherit its parent's scope, but scope: {menu: '=drSrc'} creates an isolated scope, which remove your template's access to Alerts. When you remove scope: {menu: '=drSrc'}, menu no longer exists, so scope.menu.x fails and your element is no longer draggable.
The simplest fix is to use scope: true and reference scope.drSrc.x, etc. instead of scope.menu.x. With scope: true, you get access to the parent's scope, including drSrc and the Alerts data your template is using.
These writeups are useful in understanding directives and scopes:
Angular's directive docs
Understanding Scopes
What is the difference between '#' and '=' in directive scope
I'm currently working on a project that depends heavily upon Modal Dialogs. Each with their own purpose and dynamic content.
Here's the system I have been working with:
index.html
<!doctype html>
<html ng-app="myApp" ng-controller="MainCtrl">
<head>
<title>Dialogs</title>
<link rel="stylesheet" href="app.css">
</head>
<body>
<button ng-click="openDialog()">Open Dialog</button>
<modal-dialog show="showMe" dialog-controller="WelcomeDialogCtrl" context="welcome"></modal-dialog>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script>
<script src="app.js"></script>
</body>
</html>
app.js
var app = angular.module('myApp', []);
// The main controller, which will handle index.html
app.controller('MainCtrl', ['$scope', function($scope) {
$scope.showMe = false;
$scope.openDialog = function(){
$scope.showMe = true; // Show the 'welcome' dialog
};
}]);
// The modal dialog directive
app.directive('modalDialog', [function() {
return {
controller: '#', // Bind a controller
name: 'dialogController', // Bind the controller to this attribute name
restrict: 'E',
scope: {
show: '='
},
link: function(scope, element, attrs) {
// Close this dialog (actually ng-hides it)
scope.closeDialog = function() {
scope.show = false;
};
},
templateUrl: function(element, attrs){
// I prefer to load my dialog templates from a separate folder to keep my project tidy
return 'dialogs/' + attrs.context + '.html';
}
};
}]);
// The 'welcome' dialog has its own controller with its own scope
app.controller('WelcomeDialogCtrl', ['$scope', function($scope){
// This can be called by the template that resides within the directive
$scope.exampleFunction = function(text){
console.log('Example function says: ' + text);
};
}]);
welcome.html
<div class="dialog" ng-show="show">
<div class="dialog-overlay"></div>
<div class="dialog-box">
Welcome, be sure to check out this blazin' dialog.
<button ng-click="exampleFunction('Hi!')">Say Hi!</button>
<button ng-click="closeDialog()">Close</button>
</div>
</div>
app.css
body{
background: #eee;
margin: 80px;
}
/*
* Just some fancy schmuck
*/
button{
border-radius: 5px;
background: #272;
color: #fff;
padding: 5px 12px;
border: 0;
}
/*
* The grey, transparent curtain.
*/
.dialog-overlay {
width: 100%;
height: 100%;
position: absolute;
background: #111;
opacity: 0.2;
top: 0;
left: 0;
z-index: 100;
}
/*
* The dialog itself. Horribly centered.
*/
.dialog-box{
background: #fff;
border-radius: 5px;
padding: 10px 20px;
position: absolute;
width: 600px;
height: 300px;
top: 50%;
left: 50%;
margin-left: -300px;
z-index: 110;
}
I also made a Plunker with the same code.

Rendering a Star Rating System using angularjs

My app is in this Fiddle
I need to render a star rating system dynamically from a http service, where the current stars and maximum stars can vary with each case.
Is it a good idea to create arrays from $scope.current and
$scope.max - $scope.current and pass them and run ng-repeat over them, or there is a more optimised solution than this.
Iteration ng-repeat only X times in AngularJs
Star Rating can be done either statically (read-only) or dynamically
If you want just simply to display Rating as star then try the below one
Static Star Rating
Working Example
html
<body ng-app="starApp">
<div ng-controller="StarCtrl"> <span ng-repeat="rating in ratings">{{rating.current}} out of
{{rating.max}}
<div star-rating rating-value="rating.current" max="rating.max" ></div>
</span>
</div>
</body>
script
var starApp = angular.module('starApp', []);
starApp.controller('StarCtrl', ['$scope', function ($scope) {
$scope.ratings = [{
current: 5,
max: 10
}, {
current: 3,
max: 5
}];
}]);
starApp.directive('starRating', function () {
return {
restrict: 'A',
template: '<ul class="rating">' +
'<li ng-repeat="star in stars" ng-class="star">' +
'\u2605' +
'</li>' +
'</ul>',
scope: {
ratingValue: '=',
max: '='
},
link: function (scope, elem, attrs) {
scope.stars = [];
for (var i = 0; i < scope.max; i++) {
scope.stars.push({
filled: i < scope.ratingValue
});
}
}
}
});
If you want to do Star Rating dynamically try this out
Dynamic Star Rating
Working Demo
Html
<body ng-app="starApp">
<div ng-controller="StarCtrl"> <span ng-repeat="rating in ratings">{{rating.current}} out of
{{rating.max}}
<div star-rating rating-value="rating.current" max="rating.max" on-rating-selected="getSelectedRating(rating)"></div>
</span>
</div>
</body>
script
var starApp = angular.module('starApp', []);
starApp.controller('StarCtrl', ['$scope', function ($scope) {
$scope.rating = 0;
$scope.ratings = [{
current: 5,
max: 10
}, {
current: 3,
max: 5
}];
$scope.getSelectedRating = function (rating) {
console.log(rating);
}
}]);
starApp.directive('starRating', function () {
return {
restrict: 'A',
template: '<ul class="rating">' +
'<li ng-repeat="star in stars" ng-class="star" ng-click="toggle($index)">' +
'\u2605' +
'</li>' +
'</ul>',
scope: {
ratingValue: '=',
max: '=',
onRatingSelected: '&'
},
link: function (scope, elem, attrs) {
var updateStars = function () {
scope.stars = [];
for (var i = 0; i < scope.max; i++) {
scope.stars.push({
filled: i < scope.ratingValue
});
}
};
scope.toggle = function (index) {
scope.ratingValue = index + 1;
scope.onRatingSelected({
rating: index + 1
});
};
scope.$watch('ratingValue', function (oldVal, newVal) {
if (newVal) {
updateStars();
}
});
}
}
});
There is a wonderful tutorial here for more explanation about Angular Star Rating
You can even try angular-ui. Here is the link.
Just need to add this tag.
<rating ng-model="rate" max="max"
readonly="isReadonly"
on-hover="hoveringOver(value)"
on-leave="overStar = null">
//Controller
var starApp = angular.module('starApp', []);
starApp.controller('StarCtrl', ['$scope', function ($scope) {
$scope.maxRating = 10;
$scope.ratedBy = 0;
$scope.rateBy = function (star) {
$scope.ratedBy = star;
}
}]);
.rating {
color: #a9a9a9;
margin: 0;
padding: 0;
}
ul.rating {
display: inline-block;
}
.rating li {
list-style-type: none;
display: inline-block;
padding: 1px;
text-align: center;
font-weight: bold;
cursor: pointer;
}
.rating .filled {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="starApp">
<div ng-controller="StarCtrl">
<ul class="rating">
<li ng-repeat="n in [].constructor(maxRating) track by $index">
<span ng-click="rateBy($index+1)" ng-show="ratedBy > $index" class="filled">★</span>
<span ng-click="rateBy($index+1)" ng-show="ratedBy <= $index">★</span>
</li>
</ul>
</div>
</body>
You could hold an array of objects like so:
var starApp = angular.module('starApp',[]);
starApp.controller ('StarCtrl', ['$scope', function ($scope) {
$scope.ratings = [];
var rating = {
current : 5,
max : 10
}
$scope.ratings.push(rating); // instead you would push what your http service returns into thearray.
}]);
Then in your view you could use ng-repeat like so:
<body ng-app="starApp">
<div ng-controller="StarCtrl">
<span ng-repeat="rating in ratings">{{rating.current}} out of {{rating.max}}</span>
</div>
</body>
My minimalistic approach:
The view
<head>
<!-- alternatively you may use another CSS library (like FontAwesome) to represent the star glyphs -->
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></link>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0-rc.2/angular.min.js"></script>
<!-- insert the JavaScript controller and the CSS enhancements here -->
</head>
<body>
<div ng-app="StarRatings">
<div ng-controller="myController as ctrl">
<div ng-repeat="n in ctrl.getStarArray()" ng-class="ctrl.getClass(n)" ng-mouseover="ctrl.setClass($event,n)"> </div>
<p>
You have chosen {{ctrl.selStars}} stars
</p>
</div>
</div>
</body>
Note: if you want to use the onClick event instead onMouseOver event then replace ng-mouseover with ng-click in the HTML above.
The controller
<script>
(function() {
var app = angular.module('StarRatings', []);
app.controller('myController', function() {
this.selStars = 0; // initial stars count
this.maxStars = 5; // maximum number of stars
// a helper function used within view
this.getStarArray = function() {
var result = [];
for (var i = 1; i <= this.maxStars; i++)
result.push(i);
return result;
};
// the class used to paint a star (filled/empty) by its position
this.getClass = function(index) {
return 'glyphicon glyphicon-star' + (this.selStars >= index ? '' : '-empty');
};
// set the DOM element class (filled/empty star)
this.setClass = function(sender, index) {
this.selStars = index;
sender.currentTarget.setAttribute('class', this.getClass(index));
};
});
})();
</script>
Optionally some CSS enhancements
<style>
.glyphicon {
color: gold;
cursor: pointer;
font-size: 1.25em;
}
</style>
Not convinced? Try this JSFiddle: https://jsfiddle.net/h4zo730f/2/
let app = angular.module ('myapp',[])
-
##star Rating Styles
----------------------*/
.stars {
padding-top: 10px;
width: 100%;
display: inline-block;
}
span.glyphicon {
padding: 5px;
}
.glyphicon-star-empty {
color: #9d9d9d;
}
.glyphicon-star-empty,
.glyphicon-star {
font-size: 18px;
}
.glyphicon-star {
color: #FD4;
transition: all .25s;
}
.glyphicon-star:hover {
transform: rotate(-15deg) scale(1.3);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div ng-app= "myapp" >
<div class="stars">
<div id="stars" class="star">
<span ng-repeat="x in [0,1,2,3,4,5]" ng-if="($index < 4)" class="glyphicon glyphicon-star"> </span>
<span ng-repeat="x in [0,1,2,3,4,5]" ng-if="($index >= 4 && $index < 5) " class="glyphicon glyphicon-star-empty"></span>
</div>
</div>
</div>
hmc.starRating.js
angular.module('starRatings',[]).directive('starRating', function () {
return {
restrict: 'A',
template: '<ul class="rating">' +
'<li ng-repeat="star in stars" ng-class="star">' +
'\u2605' +
'</li>' +
'</ul>',
scope: {
ratingValue: '=',
max: '='
},
link: function (scope, elem, attrs) {
console.log(scope.ratingValue);
function buildStars(){
scope.stars = [];
for (var i = 0; i < scope.max; i++) {
scope.stars.push({
filled: i < scope.ratingValue
});
}
}
buildStars();
scope.$watch('ratingValue',function(oldVal, newVal){
if(oldVal !== newVal){
buildStars();
}
})
}
}
});
<script src="hmc.starRating.js"></script>
**app.js**
var app = angular.module('app', ['ui.bootstrap', 'starRatings']);
**indix.html**
<div star-rating rating-value="7" max="8" ></div>
.rating {
color: #a9a9a9;
margin: 0 !important;
padding: 0 !important;
}
ul.rating {
display: inline-block !important;
}
.rating li {
list-style-type: none !important;
display: inline-block !important;
padding: 1px !important;
text-align: center !important;
font-weight: bold !important;
cursor: pointer !important;
width: 13px !important;
color: #ccc !important;
font-size: 16px !important;
}
.rating .filled {
color: #ff6131 !important;
width: 13px !important;
}

Categories