我有一个正常的ng-repeat模型。除了我的输入之外,其他所有东西都工作正常……输入数据后,我需要运行一个JavaScript函数。
<div class="form-group">
<input type="text" id="game-time-passed-{{$index}}" class="form-control"
readonly="true" value="{{games.gameStartTime}}">
</div>
我只是无法在输入生成后立即对其进行访问。我知道我不能在输入上使用onload ...一切完成后我可以继续使用它,但是感觉不对。我需要在数据进入输入框时立即对其进行更改,并在该输入框上注册一种带有其值的计时器。
我也可以在输入下放置一个脚本标记,并启动一个自调用函数,但是我想保持整洁。最好是一个角度属性或其他类似的东西:
<div class="form-group">
<input type="text" id="game-time-passed-{{$index}}" class="form-control"
readonly="true" input-loaded="myFunction(this)">
</div>
简而言之:当输入被加载或触发具有其值的某种事件时,是否仍然可以访问输入?普通的JavaScript会非常不错。
因此,经过一些努力,我自己找到了答案。
我正在使用一个自定义指令,当到达ng-repeat的最后一个元素并将其呈现时将触发该指令,但在浏览器中仍然看不到。就是我想做的。
这是我的解决方案:
1.通过另一个函数的名称空间注册自定义指令:
const CUSTOMDIRECTIVE = require('./CustomDirectives.js');
// Main APP:
angular.module('LoLWatcher', []);
/**
* Register Directives
*/
// Register Sepctate Timers Directive
angular.module('LoLWatcher').directive('spectateFinishedLoadingTimers', CUSTOMDIRECTIVE.spectateFinishedLoadingTimers);
2.在我的自定义指令中,我的代码现在看起来像这样:
var CUSTOMDIRECTIVES = module.exports = CUSTOMDIRECTIVES || {};
/**
* Global Variables and Modules
*/
// Error Logger
const ERRORLOGGER = require('../Helpers/ErrorLogger.js');
CUSTOMDIRECTIVES.spectateFinishedLoadingTimers = function(){
// Activate Strict Mode
'use strict';
// Add Name Parameter to Function
CUSTOMDIRECTIVES.spectateFinishedLoadingTimers.FuncName = 'CUSTOMDIRECTIVES.spectateFinishedLoadingTimers';
try {
// Return directive Object.
return {
// Restrict by Attribute.
restrict: 'A',
// Link Function to directive.
link: function (scope, element, attr) {
// If is last element in ng-repeat...
if (scope.$last) {
// ... run async callback from attribute.
scope.$evalAsync(attr.spectateFinishedLoadingTimers);
}
}
};
} catch (e) {
//Logg complete error
console.log(e);
//future user error codes
console.log(ERRORLOGGER.standardErrorLog(CUSTOMDIRECTIVES.spectateFinishedLoadingTimers.FuncName, 'functionError'));
}
};
3.之后,我不得不用我的自定义属性修改html($ last && ...确保仅在到达最后一个元素时才触发我的函数):
<div class="row-fluid" ng-model="personList" ng-repeat="person in personList| filter:featuredPersons(filter)" spectate-finished-loading-timers="$last && timersFinishedLoading()">
4.最后要做的是将我的自定义函数注册到我的控制器/作用域:
// Function fired from Attribute
$scope.timersFinishedLoading = function(){
console.log('done rendering but not loaded in browser');
// Plain easy JS!
let div = document.querySelectorAll('[id^=time-passed-]');
for(let i= 0; i < div.length; i++){
/**
* Do Stuff with Timers
*/
}
};
所有这些使我能够从所有生成的输入中获取我的值,并更改它们的值,因为它们出现在浏览器中,或者以我的电子形式出现。由于我大量使用名称空间和模块,因此省去了“脏”的部分。
最后一件事,如果你们反对一个问题,至少要写一条评论为什么要这样做并帮助其他人改善!我们都从小开始,仍然在学习...只是说说而已。
我希望这将对遇到相同问题的人有所帮助。
此致Megajin
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句