猿问

angular的Directive传值问题?

angular的Directive传值问题

RISEBY
浏览 651回答 3
3回答

翻阅古今

单纯的从你代码来看的话,只要在组件加载的时候AddMusicCtrl.stores有值,directive是可以获取到的。所以你console出undefined的原因可能是因为在directive加载的时候,AddMusicCtrl.stores并没有值。你可以尝试着这么写一下:<stores&nbsp;list="AddMusicCtrl.stores"&nbsp;data-ng-if="AddMusicCtrl.stores"></stores>或者在你的controller里面给AddMusicCtrl.stores一个默认值。

尚方宝剑之说

这里并非是“传不进去值”,而是在传值的时候AddMusicCtrl.stores这个变量还没有值。在controller中为AddMusicCtrl.stores设置一个默认值就可以解决这个问题,也可以在指令中监听一下list。当list变化时(也就是从没值变到有值得时候 ),就可以打印出来了&nbsp;&nbsp;&nbsp;link:&nbsp;function&nbsp;(scope,elem,attr)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;scope.$watch('list',function(newVlaue){ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log(scope.list) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;}在指令的编译过程中,controller指令声明了变量而未给它赋值,编译stores指令的时候,所绑定的变量还没有赋值,因而打印出 undefined。

四季花海

angular.module('index_area').directive('stores', function () {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; restrict: 'E',&nbsp; &nbsp; &nbsp; &nbsp; replace: true,&nbsp; &nbsp; &nbsp; &nbsp; scope: true,&nbsp; &nbsp; &nbsp; &nbsp; templateUrl: 'Template/StoresSelect.html',&nbsp; &nbsp; &nbsp; &nbsp; link: function (scope,elem,attr) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //var value= scope.AddMusicCtrl.stores&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(scope.AddMusicCtrl.stores)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }})<div class="form-lyout">&nbsp; &nbsp; <div class="form-title">参与区域</div>&nbsp; &nbsp; <div class="form-layout">&nbsp; &nbsp; &nbsp; &nbsp; <div class="radio">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<input type="radio" name="exclusives" value="true"&nbsp; ng-model='AddMusicCtrl.music.exclusive' checked>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 全部门店&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </label>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="radio">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<input type="radio" name="exclusives" value="true"&nbsp; ng-model='AddMusicCtrl.music.exclusive' checked>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 部分门店&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </label>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div></div><div class="form-lyout">&nbsp; &nbsp; <div class="form-title">门店筛选</div>&nbsp; &nbsp; <div class="form-layout">&nbsp; &nbsp; &nbsp; &nbsp; {{AddMusicCtrl.stores}}&nbsp; &nbsp; &nbsp; &nbsp; <store></stores>&nbsp; &nbsp; </div></div>
随时随地看视频慕课网APP

相关分类

AngularJS
我要回答