将$$ hashKey添加到Angular中的对象

时间:2014-05-06 17:29:56

标签: javascript angularjs

枚举对象$$hashKey上的Angular特定属性可用于很多事情。

例如DOM定位;

<div ng-repeat="obj in objects">
    <label for="field-{{obj.$$hashKey}}">
        Label
    </label>
    <input type="text" id="field-{{obj.$$hashKey}}" />
</div>

在我遇到的一些奇怪的情况下,即使用Angular重复,我还没有在我想要访问它的对象上设置$$ hashKey prop。 有没有办法在初始化对象时自己设置此属性?

编辑:我的猜测是存在某种形式的执行顺序问题,当Angular尚未处理重复时我会访问该属性。 我正在深深地观察一个物体,在那个物体内是一个带有物体的数组,它正在重复。它也是我需要访问$$hashKey属性所需的其中一个对象。

简单的例子;

var MyController = function($scope, Obj)
{
    $scope.obj = {
        list: [obj, obj, obj, obj]
    };

    $scope.$watch("obj", function()
    {
        var lastObj = $scope.obj.list[$scope.obj.list.length - 1];
        console.log(lastObj.$$hashKey); // Undefined?
    }, true);

    $scope.addObj = function()
    {
        $scope.obj.list.push(new Obj());
    };
};

Edit2:jsFiddle http://jsfiddle.net/2sbWp/2/

2 个答案:

答案 0 :(得分:5)

使用$ timeout且没有延迟值来推迟$$ hashKey属性可用:

$timeout(function(){console.log(lastObj.$$hashKey)});

A working fork of your Fiddle

答案 1 :(得分:0)

我根据您的代码创建了一个虚拟示例,请参见此处:http://plnkr.co/edit/9PNc6bcy1TO4Zaeyuvwq?p=preview

var app = angular.module( 'gssApp', [] );

app.controller( 'gssAppController', [ '$scope', '$http', function ( $scope, $http )
{
  var obj = {'hash': 'test'};
  $scope.newObject = {'hash': 'test'};
  $scope.model = null;

  $scope.objects = [];

  $scope.addObj = function(){
    if($scope.model !== null && $scope.model !== undefined){
      $scope.objects.push({'hash': $scope.model});
      $scope.model = '';
      angular.forEach($scope.objects, function(key, value){
        console.log(value, key);
      }); 
    }
  }; 

}] );

HTML

<body ng-app="gssApp" ng-controller="gssAppController">
    <div ng-repeat="obj in objects">
      <label for="field-{{obj.$$hashKey}}" ng-click="alert(obj.$$hashKey)">
         Label
      </label>
      <input type="text" id="field-{{obj.$$hashKey}}" />
    </div>
    <input type="text" placeholder='add new key' ng-model="model">
    <button ng-click="addObj();">Submit</button>
</body>

希望这能够揭示$$ hashkey