angular directive中link内scope中有属性但是取不出

尝试在link内的scope中取出相关属性,但是取出为undefined

图片描述

第一行的打印能打印出具体的&id
第二行也能打印出scope的内容,其中是有task的也就是说,第三行也是能打印出内容的
但是第三行打印出的内容是undefined

图片描述

具体内容如上所示

求大神解答


图片描述

阅读 4.4k
4 个回答

请用断点调试
console.log(scope)输出的并不是这句语句执行时的scope,而是记录对scope对象的引用,在你查看log时再去获取scope对象输出来
或者可以使用console.log(angular.copy(scope))或者console.log(JSON.stringify(scope))来输出日志

link: function (scope, elements, attributes) {
        console.log(scope)
        console.log(scope.slideList[0].src); // 无法访问
        
        $(function () {
            var fullWidth = scope.fullWidth;
            $('.carousel.carousel-slider').carousel({fullWidth: fullWidth});
            $(".carousel").css("height", $(".carousel a img").eq(0).height())
        })
    }

clipboard.png

修改代码

link: function (scope, elements, attributes) {
        $(function () {
            console.log(scope)
            console.log(scope.slideList[0].src); // 这样就可以加载了。
            var fullWidth = scope.fullWidth;
            $('.carousel.carousel-slider').carousel({fullWidth: fullWidth});
            $(".carousel").css("height", $(".carousel a img").eq(0).height())
        })
    }

截图

clipboard.png

原因就是数据是异步加载的,要不将异步改为同步,要不就是使用$(function(){})后加载。

使用resolve解决此问题

.state('index', {
    url: '/index',
    templateUrl: './tpls/index.tpl.html',
    resolve: {
        preSlider: function ($rootScope, $http) {
            $http.get('slide.json')
                .then((res) => {
                    $rootScope.slideList = res.data; // 在此处获取数据
                });
        }
    },
    controller: 'index.ctrl'
})

请将完整指令显示出来

$scope的task值时异步传递过来的,所以为空

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题