如何在指令范围内访问ng-repeat项的子项?

时间:2014-04-15 17:44:09

标签: angularjs angularjs-directive angularjs-ng-repeat

我刚开始使用AngularJS。我想访问div.item内的ng-repeat,但它不起作用。

编辑:当我点击addtime时,新项目应根据鼠标的位置定位

点击addTime($event)时:

  • 我在ng-repeat="t in time"

  • 中添加了一个新行
  • 我可以获得鼠标的位置

  • 但我无法将其传递给我刚刚在ng-repeat创建的项目。 我无法更新此新项目的范围myLeft

有办法吗?

的index.html

 <div class="time" addtime ng-click="addTime($event)">
   <!-- ngRepeat: t in time -->
   <div time="" ng-repeat="t in time" class="ng-scope">
       <div class="item" id="item-0" resizable draggable ng-click="click($event)" ng-style="{ width: myWidth, left: myLeft }"></div>
   </div>
   <!-- end ngRepeat: t in time -->
 </div>

JS / directive.js

 dragDirectives.directive('addtime', function() {
  return {
  restrict: 'A',
  link: function(scope, element, attr, ctrl) {

  },
  controller: function addtimeCtrl($scope, $element){
    $scope.time = [];
    $scope.addTime = function(event) {
       $scope.time.push($scope.time.length + 1);
       console.log(event.offsetX);
       // How can access to class="item" of the new ng-repeat (scope.time[])
    };
  }
 }
});

1 个答案:

答案 0 :(得分:1)

我找到了解决方案:

我将值存储在数组$scope.time[]

 $scope.time = [];
 $scope.addTime = function(event) {
     $scope.time.push(
       {
          mouseX: pos + "px"
       }
     );
 }

然后我使用 ng-repeat

获取t.mouseX中的值
<div class="time" addtime ng-click="addTime($event)">
   <!-- ngRepeat: t in time -->
   <div time ng-repeat="t in time" class="ng-scope">
       <div class="item" ng-style="{ left: t.mouseX }" resizable draggable ng-click="click($event)"></div>
   </div>
   <!-- end ngRepeat: t in time -->
 </div>