Reputation: 736
So I'm building an application with AngularJS.
I get my data from JSON. The JSON exists from data that has a label, an x coordinate, an y coordinate and a width/height.
I do this with this code in my controller.js
file:
function locationController( $scope, $http, getCss) {
$http.get('file.json').success(function(data) {
$scope.locations = data;
});
}
And I output it in my HTML like this:
<section ng-controller="locationController">
<ul>
<div ng-repeat="location in locations" ng-style="location.css()" >
<p>{{location.label}}</p>
</div>
</ul>
</section>
Now I want to make a service that generates the CSS for the div I'm repeating. It's based on the width/height x en y coordinate of the location I get from JSON.
Here is the code:
var app = angular.module('myApp', []);
app.factory('getCss', function() {
return {
css : function(x , y , value) {
return {
backgroundColor: "#333",
x: (x - value) + 'px',
y: (y - value) + 'px',
width: (value * 2) + 'px',
height: (value * 2) + 'px',
color: "#FFF"
}
}
}
});
But how do I link this service to each location?
Upvotes: 0
Views: 511
Reputation: 26880
Expose the getCss
service on the controller, like this:
function locationController( $scope, $http, getCss) {
$http.get('file.json').success(function(data) {
$scope.locations = data;
});
$scope.css = function(location) {
return getCss.css(location.x, location.y, location.value);
}
}
And on the HTML:
<div ng-repeat="location in locations" ng-style="css(location)" >
<p>{{location.label}}</p>
</div>
Upvotes: 1