gpt4 book ai didi

javascript - Angular js 指令属性未附加到指令范围

转载 作者:行者123 更新时间:2023-11-27 23:29:24 26 4
gpt4 key购买 nike

我正在尝试通过元素属性将参数传递给指令下面是一个片段:

指令

app.directive('bgFluct', function(){
var _ = {};
_.scope = {
data: "@ngData"
}
_.link = function(scope, elem, attr) {

// if there is no image provided use pp.png the default
scope.background = scope.data !== undefined ? scope.data : '../../img/pp.png'
elem.css(
{
'background': 'url('+scope.background+')',
'background-size': 'cover',
'background-repeat': 'no-repeat',
'background-position': 'center center'
})
}
return _;
})

html

<div class="four columns" style="margin-right: 20px;">
<div class="row">
<div ng-data="{{ vm.background_image }}" class="project-item" bg-fluct>
</div>
</div>
</div>

在我的指令 console.log(scope) 中打印:

scope has a data property but i cant access it by scope.data

主要问题scope有一个数据属性(下面的屏幕截图),但我无法通过scope.data访问它

我一遍又一遍地检查我的整个代码,但仍然找不到这个问题的解决方案。

如何从指令属性访问 ng-data 属性?

干杯!

最佳答案

解决您的问题的一个简单方法是使用 $timeout,通过将代码包装在超时中,您可以为摘要循环提供执行和初始化属性的时间:

$timeout(function() {
scope.background = scope.data !== undefined ? scope.data : '../../img/pp.png'
elem.css(
{
'background': 'url('+scope.background+')',
'background-size': 'cover',
'background-repeat': 'no-repeat',
'background-position': 'center center'
});
}, 0); // <== 0 timeout or some if it didn't work

另一种解决方案可能是在您的属性上注册观察者:

scope.$watch('data', function(data){/* the same as the previous example */})

关于javascript - Angular js 指令属性未附加到指令范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34698972/

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