无法传递给 angular 指令中的 onclick
Can't pass to onclick in angular directive
查看以下 angular 指令:
angular.module("mySystem").directive("pageFooter", function () {
return {
restrict: "E",
scope: { footerhref: '&' },
template: <button onclick="{{footerhref}}">{{footerhref}}</button>
}
});
<page-footer footerhref="location.href='\Home.html'" />
有人能告诉我为什么 footerhref 没有传递到 onclick 而它传递给按钮内容吗? (我不希望它出现在内容中。我刚刚添加了一个示例)。
这可以解决吗?
如果我只是创建一个如下所示的按钮,它就可以工作:
<button onclick="location.href = '\Home.html'">Using onclick without Angular</button>
这就是我试图让 angular 指令呈现的方式。
onclick
需要函数调用而不是解析为字符串的表达式。
您必须使用 &
而不是 @
,因为我们传递的是可执行代码行而不是字符串。
您将不得不使用 ng-click
而不是 onclick
。基于 documentation onclick
不起作用的原因是:
Interpolations for HTML DOM event attributes are disallowed. Please
use the ng- versions (such as ng-click instead of onclick) instead.
此外,将 templateUrl
更改为 template
,因为您提供的是内联模板
您必须在 $scope 中设置位置引用,因为您正试图从 UI 标记 <page-footer footerhref="location.href='\Home.html'" />
访问 location
app.directive("pageFooter", function ($compile) {
return {
restrict: "E",
scope: { footerhref: '&', caption: '@' },
template: '<button ng-click="footerhref()">{{caption}}</button>'
}
});
<page-footer footerhref="location.href='\Home.html'" caption="Home"></page-footer>
$scope.location = location; // In your controller
查看以下 angular 指令:
angular.module("mySystem").directive("pageFooter", function () {
return {
restrict: "E",
scope: { footerhref: '&' },
template: <button onclick="{{footerhref}}">{{footerhref}}</button>
}
});
<page-footer footerhref="location.href='\Home.html'" />
有人能告诉我为什么 footerhref 没有传递到 onclick 而它传递给按钮内容吗? (我不希望它出现在内容中。我刚刚添加了一个示例)。
这可以解决吗?
如果我只是创建一个如下所示的按钮,它就可以工作:
<button onclick="location.href = '\Home.html'">Using onclick without Angular</button>
这就是我试图让 angular 指令呈现的方式。
onclick
需要函数调用而不是解析为字符串的表达式。
您必须使用 &
而不是 @
,因为我们传递的是可执行代码行而不是字符串。
您将不得不使用 ng-click
而不是 onclick
。基于 documentation onclick
不起作用的原因是:
Interpolations for HTML DOM event attributes are disallowed. Please use the ng- versions (such as ng-click instead of onclick) instead.
此外,将 templateUrl
更改为 template
,因为您提供的是内联模板
您必须在 $scope 中设置位置引用,因为您正试图从 UI 标记 <page-footer footerhref="location.href='\Home.html'" />
location
app.directive("pageFooter", function ($compile) {
return {
restrict: "E",
scope: { footerhref: '&', caption: '@' },
template: '<button ng-click="footerhref()">{{caption}}</button>'
}
});
<page-footer footerhref="location.href='\Home.html'" caption="Home"></page-footer>
$scope.location = location; // In your controller