我在一个ionic项目中使用carousel (https://market.ionic.io/plugins/morph-carousel)。这是一个自定义的angularjs指令。我在一个屏幕上使用2个旋转木马。现在,我想要的是在更改第一个轮播时,第二个轮播也应该更新为新值。为此,必须重新加载/刷新第二个轮播自定义指令。有没有办法刷新/重新加载angularjs中的自定义指令?
发布于 2016-04-03 03:27:54
在link函数的第一个指令中添加一个监视器。
scope.$watch('thingToWatchForRefershing', function (newValue, oldValue) {
if (!newValue || angular.equals(newValue, oldValue)) {
return;
}
scope.$emit('somethingChangedInFirstDirective', dataToBePassed);
});现在,在您的第二条指令中,有一个渲染函数,当调用该函数时,它将刷新模型和视图,并添加一个侦听器。
link: function () {
scope.render = function () {
// all logic goes here
};
scope.$on('somethingChangedInFirstDirective', function (ev, data) {
// render everything again i.e. reload the directive
scope.render();
});
// first time rendering
scope.render();
}希望它能有所帮助:)
更新:
<custom-carousel data-is-to-be-watched="isToBeWatched" />,在您的控制器集中:$scope.isToBeWatched = true。另外,对于第二个指令的用法:<custom-carousel data-is-tobe-reloaded="isToBeReloaded" />和在同一个控制器中初始化:$scope.isToBeReloaded = false;scope:{isToBeWatched: '=?', isToBeReloaded: '=?'}, link: function (...) {...}<custom-carousel data-is-tobe-reloaded="isToBeReloaded" />,is if (scope.isToBeWatched),这意味着第一个指令被加载/更改,因为我们只在第一个指令中传递了attr。现在,发出一个事件,它将在控制器中被监听。在侦听器do:$scope.isToBeReloaded = true;中,它将在第二个指令的作用域中设置变量isToBeReloaded,因为我们在第二个isToBeReloaded中传递了一个监视器,并重新加载了我前面提到的呈现fn。粗略代码:
控制器:
$scope.isToBeWatched = true;
$scope.isToBeReloaded = false;
$scope.$on('somethingChangedInFirstDirective', function () {
$scope.isToBeReloaded = true;
});指令:
scope: {
isToBeWatched: '=?',
isToBeReloaded: '=?'
},
link: function (scope) {
scope.render = function () {
if (scope.isToBeWatched) {
scope.$emit('somethingChangedInFirstDirective');
}
};
scope.render();
scope.$watch('isToBeReloaded', function (newValue, oldValue) {
if (!newValue || angular.equals(newValue, oldValue))
return;
scope.render();
})
}https://stackoverflow.com/questions/36377578
复制相似问题