gpt4 book ai didi

javascript - 指令链接函数中未定义的范围变量

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

我有一个包含这段代码的指令:

return {
restrict: "E",
scope: {
moduleProgress: "=",
modules: "=",
parentScroll: "="
},
templateUrl: 'app/program/module.list.template.html',
link: function(scope,el,attrs,ctrl,tf) {
$templateRequest("app/program/chapter.list.template.html").then(function(template) {
var template = angular.element(template);
var elements = [];

console.log(scope);

attrs.$observe("modules", function(val) {
scope.modules.forEach(function(module) {
module.open = false;
});
});

出于某种原因,我第一次导航到包含此指令的 View 时一切正常,但从第二次开始我总是收到 Cannot call method 'forEach' of undefined 错误。我通读了一些关于 SO 的类似问题,其中提到插值属性不能在链接函数上立即可用,因此他们建议使用 $observe。我什至添加了 console.log(scope) 并且 modules 属性显示在对象上。知道是什么原因造成的吗?

最佳答案

它应该是 $scope.$watch 而不是 attrs.$observe 因为 $observe 需要 @ 在独立的指令范围内 & 在 html 上它将是 modules="{{module}}",对于大对象 DOM 会变得困惑所以我更喜欢你使用 $watch 有道理

代码

scope.$watch("modules", function(newVal) {
if(newVal){
scope.modules.forEach(function(module) {
module.open = false;
});
}
});

关于javascript - 指令链接函数中未定义的范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31538107/

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