如何在angularjs指令中运行函数
我有这个指示:如何在angularjs指令中运行函数,angularjs,Angularjs,我有这个指示: .directive('reorderDiv', function ($compile) { return function (scope, elem, attrs) { function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // Elemente while
.directive('reorderDiv', function ($compile) {
return function (scope, elem, attrs) {
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// Elemente
while (0 !== currentIndex) {
// Die restlichen Elemente
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
elem.on('click', function () {
console.log('called');
var divs = angular.element(document.querySelector('.center'));
console.log(divs);
divs = shuffle(divs);
var content = $compile(divs)(scope);
elem.append(content);
})
}
})
我的目标是,如果视图加载,它应该运行函数shuffle
,而不是单击元素。我该怎么做
我试图使用
elem.on(“load”)[…]
,但这不起作用。谁能给我解释一下,为什么这不起作用 只需在指令中使用正确的参数调用shuffle
函数即可。它将运行。当指令加载时,您可以使用$onInit事件启动随机播放功能:
.directive('reorderDiv', function($compile) {
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// Elemente
while (0 !== currentIndex) {
// Die restlichen Elemente
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
var obj = {
controller: function() {
this.$onInit = function() {
var divs = angular.element(document.querySelector('.center'));
console.log(divs);
shuffle(divs);
}
},
link: function(scope, elem, attrs) {
elem.on('click', function() {
console.log('called');
var divs = angular.element(document.querySelector('.center'));
console.log(divs);
divs = shuffle(divs);
var content = $compile(divs)(scope);
elem.append(content);
})
}
};
return obj;
})
只需在
点击事件后调用shuffle函数..嗯,这不起作用。同样在刷新之后..检查这个不起作用的。我删除了on.click。日志会被调用,但div不会重新排序代码>或洗牌(divs)代码>?像这样:divs=shuffle(divs);变量内容=$compile(divs)(范围);元素附加(内容)代码>当我用shuffle(divs)调用它时代码>也没有发生任何事情。有没有办法在视图加载时启动它?