javascript - angular的Directive传值问题
阿神
阿神 2017-04-11 12:24:55
[JavaScript讨论组]

小弟用Direcrive做了一个组件,在demo上测试运行过没问题。但是放在项目上使用后发现传值传不进去。
先附上异常问题代码

angular.module('index_area').directive('stores', function () {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            list:"="
        },
        templateUrl: 'Template/StoresSelect.html',
        link: function (scope,elem,attr) {
            console.log(scope.list)
        }
    }
})


参与区域

门店筛选

{{AddMusicCtrl.stores}}

为了找到问题的所在我专门测试了。发现它是有值得。

{{AddMusicCtrl.stores}}

但是到了。这里就显示undefined了。如果我

改成

我发现list可以将11传进去。请问下是为什么呢?怎么解决

阿神
阿神

闭关修行中......

全部回复(3)
怪我咯

单纯的从你代码来看的话,只要在组件加载的时候AddMusicCtrl.stores有值,directive是可以获取到的。
所以你console出undefined的原因可能是因为在directive加载的时候,AddMusicCtrl.stores并没有值。
你可以尝试着这么写一下:

<stores list="AddMusicCtrl.stores" data-ng-if="AddMusicCtrl.stores"></stores>

或者在你的controller里面给AddMusicCtrl.stores一个默认值。

伊谢尔伦

这里并非是“传不进去值”,而是在传值的时候AddMusicCtrl.stores这个变量还没有值。在controller中为AddMusicCtrl.stores设置一个默认值就可以解决这个问题,也可以在指令中监听一下list。当list变化时(也就是从没值变到有值得时候 ),就可以打印出来了

   link: function (scope,elem,attr) {
          scope.$watch('list',function(newVlaue){
               console.log(scope.list)
          })
           
    }

在指令的编译过程中,controller指令声明了变量而未给它赋值,编译stores指令的时候,所绑定的变量还没有赋值,因而打印出 undefined。

PHPz
angular.module('index_area').directive('stores', function () {
    return {
        restrict: 'E',
        replace: true,
        scope: true,
        templateUrl: 'Template/StoresSelect.html',
        link: function (scope,elem,attr) {
            //var value= scope.AddMusicCtrl.stores
            console.log(scope.AddMusicCtrl.stores)
        }
    }
})


<p class="form-lyout">
    <p class="form-title">参与区域</p>
    <p class="form-layout">
        <p class="radio">
            <label>
                 <input type="radio" name="exclusives" value="true"  ng-model='AddMusicCtrl.music.exclusive' checked>
                    全部门店
            </label>
        </p>
        <p class="radio">
            <label>
                 <input type="radio" name="exclusives" value="true"  ng-model='AddMusicCtrl.music.exclusive' checked>
                    部分门店
            </label>
        </p>
    </p>
</p>
<p class="form-lyout">
    <p class="form-title">门店筛选</p>
    <p class="form-layout">
        {{AddMusicCtrl.stores}}
        <store></stores>
    </p>
</p>

试下

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号