[英]Add $$hashKey to object in Angular
The Angular-specific property on enumerated objects $$hashKey
can be used for a lot of things. 枚举对象
$$hashKey
上特定于Angular的属性可以用于很多事情。
For example DOM-targeting; 例如DOM定位;
<div ng-repeat="obj in objects">
<label for="field-{{obj.$$hashKey}}">
Label
</label>
<input type="text" id="field-{{obj.$$hashKey}}" />
</div>
In some weird case I am experiencing now the $$hashKey prop is not yet set on a object I want to access it on even though it is being repeated with Angular. 在某些奇怪的情况下,我现在遇到$$ hashKey prop尚未设置在我想访问它的对象上,即使它已被Angular重复使用。 Is there a way to set this property yourself when initializing the object?
初始化对象时,是否可以自行设置此属性?
Edit: My guess is that there is some form of execution order issue, that I access the property when Angular has yet to process the repetition. 编辑:我的猜测是有某种形式的执行顺序问题,当Angular尚未处理重复时,我访问属性。 I am deep watching an object, within that object is an array with objects which is getting repeated.
我正在深入地观察一个对象,在该对象内是一个数组,该数组具有重复出现的对象。 It's also on one of those objects that I need to access the
$$hashKey
property on. 它也位于我需要访问
$$hashKey
属性的那些对象之一上。
Simple example; 简单的例子;
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/ Edit2:jsFiddle http://jsfiddle.net/2sbWp/2/
Use $timeout with no delay value to defer until the $$hashKey property is available: 使用$ timeout且没有延迟值,直到$ hashKey属性可用为止:
$timeout(function(){console.log(lastObj.$$hashKey)});
I created a dummy example based on you code, see here: http://plnkr.co/edit/9PNc6bcy1TO4Zaeyuvwq?p=preview 我根据您的代码创建了一个虚拟示例,请参见此处: 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 的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>
Hopefully this sheds some light on the $$hashkey 希望这可以为$$ hashkey带来一些启发
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.