我正在尝试创建一个具有隔离范围的可重用进度条指令。该指令将具有启动、停止和重置进度条的公共(public)函数。该指令将在ng-repeat
内使用
这是指令的定义:
chatApp.directive('jsProgress', function() {
var Stopwatch = function(options, updateCallback) {
// var timer = createTimer(),
var offset, clock, interval;
// default options
options = options || {};
options.delay = options.delay || 1;
// initialize
reset();
function start() {
if (!interval) {
offset = Date.now();
interval = setInterval(update, options.delay);
}
}
function stop() {
if (interval) {
clearInterval(interval);
interval = null;
}
}
function reset() {
clock = 0;
// render(0);
}
function update() {
clock += delta();
// render();
updateCallback();
}
function delta() {
var now = Date.now(),
d = now - offset;
offset = now;
return d;
}
// public API
this.start = start;
this.stop = stop;
this.reset = reset;
this.update = update;
};
return {
restrict : 'AE',
replace : true,
scope: { api: '=', key: '@'},
template: '<div class="dot" ng-attr-id="dots"><ul id="{{key}}" data-currentState="2"><li class="dot-red"></li><li></li><li></li><li></li></ul></div>',
link : function($scope, elem, attr) {
var timer = new Stopwatch( {delay: 5000}, updateCallback);
timer.start();
function updateCallback()
{
var currentCount;
currentCount = $(elem).find('#' + $scope.key).attr('data-currentState');
currentCount++;
$(elem).find('#' + $scope.key).attr('data-currentState',currentCount);
$(elem).find('#' + $scope.key+' li:nth-child(' + currentCount + ')').addClass('dot-red');
}
$scope.api =
{
reset: function()
{
timer.reset();
},
start: function()
{
timer.start();
},
stop: function()
{
timer.stop();
}
};
}
};
});
这就是它在 ng-repeat 中的使用方式
<js-progress api="{{activeUserId}}" key="{{activeUserId}}_{{activeCompanyId}}" />
现在我想在 ng-repeat 中获取指令的特定实例,并调用其公共(public) API 来启动、停止和重置特定的进度条。我怎样才能做同样的事情?在上面的定义中,它不允许我使用变量 {{activeUserId}} 因为我想在 ng-repeat 中单独引用每个实例。
最佳答案
您正在覆盖从您的 Ctrl 传递到您的指令的 activeUserId
这行:
$scope.api = {};
我认为您应该以这种方式跟踪 Controller 中的 api 对象:
在你的 Controller 中
$scope.bars = [
{
activeUserId: "id",
activeCompanyId: "companyId",
api: {} //this allows angularjs to reuse this object instance
},
{
activeUserId: "id2",
activeCompanyId: "companyId2",
api: {} //this allows angularjs to reuse this object instance
},
];
Controller 的 html 模板
<div ng-repeat="b in bars">
<js-progress api="b.api" your-extra-params-here />
</div>
稍后在您的 Controller 中,您将能够执行以下操作:
$scope.bars[0].api.start();
关于javascript - 引用指令中的范围变量双向数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29934851/