Check out this fiddle to see examples of both methods (using color as position is more challenging in jsfiddle)
Approach 1: Utilizing ng-style and a Scope Function
With ng-style, you can achieve this effect. To maintain cleanliness and testability, it's recommended to define a scope function like the one below (ternary operators are currently not supported in angular expressions for stable versions of angular 1.0.x, though ternary support has been added in 1.1.5).
ng-style='myStyleFunction($last)'
In the controller, define:
$scope.myStyleFunction = function($last) {
return {
'left': $last ? $scope.lastX + 'px' : '',
'top': $last ? $scope.lastY + 'px' : ''
};
}
Approach 2: Creating Custom Directives
Alternatively, you can take a more "angular" approach by defining a directive:
dirModule.directive('positionLast', function() {
return {
scope: true,
link: function (scope, $element, attrs) {
if (scope.$last) {
// If jQuery is available, use this. Otherwise, adjust accordingly
$element.css("left", $scope.lastX + 'px');
$element.css("top", $scope.lastY + 'px');
}
}
}
});
and then:
<div ng-repeat="contact in jsonContacts" position-last> ...
EDIT This method works by using scope: true
and declaring the directive on the ng-repeat
element. Since only one new scope is created for all directives on an element (assuming at least one requests a new scope), it gains access to the ng-repeat
scope values. Refer to the following documentation for more details:
scope - If set to true, a new scope will be created for this directive. If multiple directives on the same element request a new scope, only one new scope is created.