条件角度NG-重复添加样式样式、角度、条件、NG

由网友(蹲街、等天黑)分享简介:我使用div的名单上NG-重复,我手动添加的JSON的项目,它的渲染这个div的。我需要的最后一个分区,我在JSON添加的位置,它会自动rendiring屏幕,其中病程光标在和他们的休息停留在同样的位置,但没有让步正在呈现它的JSON的位置。i am using ng-repeat on a list of divs...

我使用div的名单上NG-重复,我手动添加的JSON的项目,它的渲染这个div的。我需要的最后一个分区,我在JSON添加的位置,它会自动rendiring屏幕,其中病程光标在和他们的休息停留在同样的位置,但没有让步正在呈现它的JSON的位置。

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>

但是当我做到这一点,所有的div得到这个位置,所以我需要使用$最后一个变量与那些左和顶部的CSS添加或删除样式标记,使一个条件。

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!

推荐答案

的看到这个 小提琴 对于这两种方法的例子(用颜色位置在的jsfiddle更难)的

选项1:NG-的风格和功能范围

NG-风格将让你这样做,并保持它整洁和可测试的,你应该定义范围的功能,如下面(三元运营商的当前未在角前pressions的角度,的虽然1.1.5增加了三元支持)。

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)'

在控制器中,定义了:

$scope.myStyleFunction = function($last) {
  return {
    'left': $last ? $scope.lastX + 'px' : '',
    'top': $last ? $scope.lastY + 'px' : ''
  };
}

选项2:自定义指令

或者,你可以想到更多的角,并定义一个指令:

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');
            }
        }
    }
});

和则:

<div ng-repeat="contact in jsonContacts" position-last> ...

真正,并宣布在指令NG重复元素。因为只有一个新的范围为元素上的所有指令创建(假设至少有一个请求一个新的范围内),然后它会进入的 NG-重复范围值。对于相关文件见:

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:

指令:指令定义对象(范围/真) Directives: Directive Definition Object (scope / true)

范围 - 如果设置为true,一个新的范围将这个指令创建。如果同一元素的多个指令,要求新的范围,只创建一个新的作用域。

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.