2013-07-05 66 views
1

我想用ui-bootstrap modal製作一個可重用的指令。如何將對象傳遞給angularjs中的指令模板?

它除了選擇

在這裏工作幾乎是指令:

directive('update', function() { 
return { 
    restrict: "E", 
    templateUrl: "tplModal.html", 
    scope: { 
    selected:"=" 
    }, 
    link: function(scope, elm, attr){ 
    scope.open = function (obj) { 
     scope.shouldBeOpen = true; 
    }; 

    scope.close = function() { 
     scope.shouldBeOpen = false; 
    }; 

    scope.opts = { 
     backdropFade: true, 
     dialogFade:true 
    }; 
    } 
} 

})

和tplModal.html

<button class='btn' ng-click='open(selected)'>Update</button> 
    <div modal="shouldBeOpen" close="close()" options="opts"> 
     <div class="modal-header"> 
      <h3><i class="lead" icon="{{selected.type}}"></i> {{selected.name}}</h3> 
     </div> 
     <div class="modal-body"> 
      <!-- stuffs here --> 
     </div> 
     <div class="modal-footer"> 
      <button class="btn btn-warning cancel" ng-click="close()">Cancel</button> 
     </div> 
    </div> 

儘管scope.opts,沒有淡化效果。

這裏是整個代碼: http://plnkr.co/edit/Ab4BOH?p=preview

我到底做錯了什麼?

+0

後這裏的代碼,告訴你如何使用該指令,告訴你所期望的代碼做什麼,以及它做了什麼。 –

+0

我更新了問題 –

+0

你的plunk不起作用,我得到了「Plunk not found」錯誤。 –

回答

0

的問題是,你在opts屬性添加到範圍後聯功能,這將後模態指令的鏈接函數調用,所以模態指令將永遠不會得到這些選項。

的解決方案是將scope.opts = ...預連接功能

directive('update', function() { 
    return { 
     ... 
     compile: function() { 
      return { 
       pre: function(scope, elm, attr){ 
        ... 
        scope.opts = { 
         backdropFade: true, 
         dialogFade: true 
        }; 
       } 
      }; 
     } 
    } 
} 

http://plnkr.co/edit/iZaEiM?p=preview

+0

非常感謝!在過去的幾個小時裏,我一直在顛倒這個問題,而且我的答案還很遙遠。現在,如果我使用模態內的另一個組件(例如,ui-bootstrap datepicker或ngUpload),我應該把相關函數放在這個預鏈接函數中嗎? –

+0

@desgnl你可以但你不必把函數放在預先鏈接函數中,它實際上取決於你的函數何時被調用。如果函數稍後會被調用,例如事件處理程序,那麼在後鏈接函數中定義它們是安全的。 –