[英]Unable to access AngularJS attribute in directive
I'm currently trying to implement a very simple directive in AngularJS. 我目前正在尝试在AngularJS中实现一个非常简单的指令。 In the end, I want to be able to use the directive like this: 最后,我希望能够使用如下指令:
<share-buttons url="google.com"></share-buttons>
My directive looks like this (coffee script): 我的指令如下所示(咖啡脚本):
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
}
And here's my template (Jade): 这是我的模板(Jade):
.social-icons
button.btn.btn-li(ng-click="share()")
i.fa.fa-linkedin.fa-fw
When I click the button, the correct function is called ($scope.share), but the only thing logged is undefined
. 当我单击按钮时,正确的函数称为($ scope.share),但记录的唯一内容是undefined
。
Can you help me? 你能帮助我吗?
its because your url
attribute is two way data bound with "=" 这是因为您的url
属性是绑定有“ =”的双向数据
so it's looking for a scope variable like this: 所以它正在寻找这样的范围变量:
$scope.google.com = // should be some value.
to be passed from the controller to the directive. 从控制器传递到指令。
If you want a string to be passed, use "@" for one way binding 如果要传递字符串,请使用“ @”进行单向绑定
scope: {
url: '@'
}
Note: you can also access it via attributes in the link function of the directive (which you don't have above) 注意:您也可以通过指令的链接功能中的属性来访问它(上面没有)
// 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.