gpt4 book ai didi

javascript - Angular 指令模板的增量值

转载 作者:行者123 更新时间:2023-11-29 23:49:00 25 4
gpt4 key购买 nike

这是我的问题,我想将带有模板的指令应用于页面上具有增量值的元素。

我的问题是我的值保持为 0,我在 stackoverflow 上尝试了很多答案但没有成功,我对 angular 很陌生。

这是我的指令:

app.directive('loader', function ($window) {

return {
restrict: 'E',
replace: true,
transclude: true,
controller: function($scope){
if (!$scope.counter)
$scope.counter = 0;
else
$scope.counter++;
},
template: '<div ng-class=\"({ \'display-opacity\' : ready{{counter}} })\" ng-transclude></div>',
};

});

根据要求,这是我的哈巴狗模板:

loader
| test
loader
| test

最佳答案

在阅读了关于 transclude 选项的文档之后,我打算写点东西(见下文),但是在玩弄 codepen 之后,我变得更加困惑了。我认为,您要尝试做的事情相当困难。

一个快速(也可能是肮脏的)解决方案是为您的柜台使用服务。 https://codepen.io/anon/pen/vxwpxo

app.directive('loader', function(myCounter) {
return {
restrict: 'E',
replace: true,
scope: {},
template: '<div>{{opacity}}</div>',
link: function(scope) {
scope.opacity = myCounter.get();
}
};
});

app.factory('myCounter', function() {
var counter = 0;

return {
get: function() {
return counter++;
}
};
});

以前的想法:

The transclude option changes the way scopes are nested. It makes it so that the contents of a transcluded directive have whatever scope is outside the directive, rather than whatever scope is on the inside. In doing so, it gives the contents access to the outside scope.

Note that if the directive did not create its own scope, then scope in scope.name = 'Jeff'; would reference the outside scope and we would see Jeff in the output.

https://code.angularjs.org/1.4.6/docs/guide/directive

我不知道,如果在定义了 counter 的指令之外有一个 Controller 。如果是,指令 Controller 中的代码将不会更改 counter 的值(如果我正确理解了文档)。如果不是,则每个指令将实例化自己的 counter,并且因为尚未设置 if (!$scope.counter) 将始终为 true。如果指令是否具有隔离范围,它的行为会有所不同。我越来越糊涂了!

关于javascript - Angular 指令模板的增量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43254681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com