[英]Unable to access AngularJS attribute in directive
我目前正在嘗試在AngularJS中實現一個非常簡單的指令。 最后,我希望能夠使用如下指令:
<share-buttons url="google.com"></share-buttons>
我的指令如下所示(咖啡腳本):
module.directive 'shareButtons', () ->
controller = ['$scope', ($scope) ->
$scope.share = () ->
console.log $scope.url
]
return {
restrict: 'EA'
scope: {
url: '=url'
}
templateUrl: viewpath_common('/directives/share-buttons')
controller: controller
}
這是我的模板(Jade):
.social-icons
button.btn.btn-li(ng-click="share()")
i.fa.fa-linkedin.fa-fw
當我單擊按鈕時,正確的函數稱為($ scope.share),但記錄的唯一內容是undefined
。
你能幫助我嗎?
這是因為您的url
屬性是綁定有“ =”的雙向數據
所以它正在尋找這樣的范圍變量:
$scope.google.com = // should be some value.
從控制器傳遞到指令。
如果要傳遞字符串,請使用“ @”進行單向綁定
scope: {
url: '@'
}
注意:您也可以通過指令的鏈接功能中的屬性來訪問它(上面沒有)
// like so
restrict: 'EA'
scope: {
url: '@'
}
templateUrl: "someURL",
link: function(scope, elem, attrs) {
console.log(attrs.url);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.