gpt4 book ai didi

AngularJS - 如何从链接函数访问隔离范围?

转载 作者:行者123 更新时间:2023-12-03 08:19:00 24 4
gpt4 key购买 nike

考虑以下指令示例:(Live Demo)

app.directive('phone', function() {
return {
restrict: 'E',
scope: {
tel: '@'
},
template: '<div>{{tel}}</div>',
link: function(scope, element, attrs) {
console.log(scope.tel); // undefined
}
};
});

这样使用:

<phone tel="1234"></phone>

tel 在模板中是可访问的,但在链接函数中它是undefined。为什么?我如何从链接函数访问隔离范围?

最佳答案

在链接函数完成之前它不会被插值(我不确定这是为什么),但你有几个选择:

app.directive('phone', function($timeout, $interpolate) {
return {
restrict: 'E',
scope: {
tel: '@'
},
template: '<div>{{tel}}</div>',
link: function(scope, element, attrs) {

//Use $timeout service with no delay:
$timeout(function(){
console.log(scope.tel); // 1234
});

//Use $watch - will get called every time the value changes:
scope.$watch('tel',function(tel){
console.log(scope.tel); // 1234
});

//You can even use the $intrapolate service, this is basically what `@` does:
console.log($interpolate(element.attr('tel'))(scope.$parent));

// in your example tel isn't an expression but a constant so you could also do this:
console.log(attrs.tel); // 1234
}
};
});

关于AngularJS - 如何从链接函数访问隔离范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16773125/

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