Reputation: 11234
I am trying to print multiple *
based on rating value. In Javascript console Array(10).join('*')
produces 10 stars. When using it in Angularjs view, this expression is not evaluated. Am I missing something?
<div data-ng-controller="SkillsController">
<ul>
<li data-ng-repeat="skill in skills">{{skill.name}} - {{Array(skill.rating).join('*')}}</li>
</ul>
</div>
App.js
app.controller('SkillsController', function($scope){
$scope.skills = [
{ name: 'Ruby', rating: 5 },
{ name: 'Java', rating: 10}
];
})
Upvotes: 0
Views: 38
Reputation: 457
From my point of view, the best way to create a method in $scope of controller to get rating transformed as you wish. From this method call another method placed in service. Thus, you'll separate business logic from presentation logic and from view.
So, View
<div data-ng-controller="SkillsController">
<ul>
<li data-ng-repeat="skill in skills">{{skill.name}} - {{ getRating(skill) }}</li>
</ul>
</div>
Controller
app.controller('SkillsController', function($scope, myService){
$scope.skills = [
{ name: 'Ruby', rating: 5 },
{ name: 'Java', rating: 10}
];
$scope.getRating = function (skill) {
return myService.transformRatings(skill.rating);
}
});
Service:
app.service('myService', function(){
return {
transformRatings: function (stars) {
return Array(stars).join('*');
}
}
});
Upvotes: 1
Reputation: 40863
Array is not part of the $scope. You can do the following in your controller.
app.controller('SkillsController', function($scope){
$scope.skills = [
{ name: 'Ruby', rating: 5 },
{ name: 'Java', rating: 10}
];
$scope.Array = Array;
});
I would however do this transformation in a filter or directive.
app.filter('stars', function() {
return function(input) {
return Array(input).join('*');
};
});
And then
{{skill.rating | stars}}
Upvotes: 2