我想要一个 AngularJS 组件,messageDisplay
,它可以带有一个属性 message
(就像在 index.html 中它的 HTML 标签上的一个属性)。 html 文件),然后显示它。根据我能够找到的所有示例代码,这应该有效,但它不起作用。
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Angular sandbox</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
<script src="app.js"></script>
<script src="components/message-display.component.js"></script>
</head>
<body ng-app="app">
<message-display message="Hi"></message-display>
</body>
</html>
应用程序.js
const app = angular.module("app", []);
消息显示.component.js
app.component(
"messageDisplay",
{
bindings: {
message: "<"
},
template: "<h1>Message: {{$ctrl.message}}</h1>"
}
)
我只得到一个包含文本“消息:”的页面,没有其他内容。我希望收到“消息:嗨”。
最佳答案
要将字符串传递给单向 ( "<"
) 绑定(bind),请使用单引号:
<message-display message="'Hi'"></message-display>
否则它将被评估为 AngularJS 表达式,例如$scope.Hi
演示
angular.module("app",[])
.component(
"messageDisplay",
{
bindings: {
message: "<"
},
template: "<h1>Message: {{$ctrl.message}}</h1>"
}
)
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<message-display message="'Hi'"></message-display>
</body>
更新
Where would you recommend I learn this stuff? The whole "bindings" concept and these mysterious <, &, =, @ symbols don't seem to be covered in the tutorial
有关详细信息,请参阅
- > AngularJS Comprehensive Directive API Reference - scope
- > AngularJS Developer Guide - Component-based application architecture
一般来说,我会避免双向 ("="
) 绑定(bind),因为这会使迁移到 Angular 2+ 变得更加困难。
出于一致性原因,我还避免了属性 ( "@"
) 绑定(bind)。我不需要记住哪些属性采用 AngularJS 表达式以及哪些属性需要 mustache ({{ }}
)。
关于javascript - 为什么我无法通过绑定(bind)将数据获取到我的 AngularJS 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51909476/