我目前正在尝试在 AngularJS 中实现一个非常简单的指令。 最后,我希望能够使用这样的指令:
<share-buttons url="google.com"></share-buttons>
我的指令如下所示( CoffeeScript ):
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),但唯一记录的内容是未定义
。
你能帮我吗?
最佳答案
这是因为您的 url
属性是与“=”绑定(bind)的双向数据
所以它正在寻找像这样的范围变量:
$scope.google.com = // should be some value.
从 Controller 传递到指令。
如果要传递字符串,请使用“@”进行单向绑定(bind)
scope: {
url: '@'
}
注意:您还可以通过指令的链接函数中的属性来访问它(上面没有)
// like so
restrict: 'EA'
scope: {
url: '@'
}
templateUrl: "someURL",
link: function(scope, elem, attrs) {
console.log(attrs.url);
}
关于javascript - 无法访问指令中的 AngularJS 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29394923/