Reputation: 1205
i am using ng-repeat on a list of divs and i am manually adding items in the json that it's rendering this divs. I need to position the last div that i add in json and it's automatically rendiring on the screen, where the couse cursor is, and the rest of them remain on same position, but without giving the position in the json that is rendering it.
My approach on this was something like this
<div ng-repeat="contact in jsonContacts" style="left: {{lastX}}px; top: {{lastY}}px;"></div>
but when i do this, all the divs get this position, so i need to make a condition using $last variable to add or remove the style tag with those left and top css.
Thank you in advance, Daniel!
Upvotes: 3
Views: 12211
Reputation: 42669
Based on you html, you should try this
<div ng-repeat='contact in jsonContacts' ng-style='{"left":($last?lastX:null)+"px","top":($last?lastY:null)+"px"}'>{{item}}</div>
Here is the fiddle for confirmation http://jsfiddle.net/cmyworld/yFc6J/1/
Upvotes: 5
Reputation: 19161
See this fiddle for examples of both approaches (using color as position is harder in jsfiddle)
Option 1: ng-style and a scope function
ng-style will let you do this, and to keep it tidy and testable you should define a scope function such as below (ternary operators are not currently supported in angular expressions for stable 1.0.x versions of angular, although 1.1.5 has added ternary support).
ng-style='myStyleFunction($last)'
In the controller, define:
$scope.myStyleFunction = function($last) {
return {
'left': $last ? $scope.lastX + 'px' : '',
'top': $last ? $scope.lastY + 'px' : ''
};
}
Option 2: custom directives
Or, you could think even more "angular" and define a directive:
dirModule.directive('positionLast', function() {
return {
scope: true,
link: function (scope, $element, attrs) {
if (scope.$last) {
// if jQuery is present use this, else adjust as appropriate
$element.css("left", $scope.lastX + 'px');
$element.css("top", $scope.lastY + 'px');
}
}
}
});
and then:
<div ng-repeat="contact in jsonContacts" position-last> ...
EDIT This works by using scope: true
and declaring the directive on the ng-repeat
element. As only one new scope is created for all directives on an element (assuming at least one requests a new scope) then it gets access to the ng-repeat
scope values. For the relevant documentation see:
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.
Upvotes: 4