我想创建一个简单的列表,当用户点击一个按钮时,该值显示在一个 span 元素中。
HTML 和 Controller
<html xmlns:ng="http://angularjs.org">
<script src="http://code.angularjs.org/angular-0.9.19.js" ng:autobind></script>
<script type="text/javascript">
function MyController(){
this.list = [{name:"Beatles", songs: ["Yellow Submarine", "Helter Skelter", "Lucy in the Sky with Diamonds"]}, {name:"Rolling Stones", songs:["Ruby Tuesday", "Satisfaction", "Jumpin' Jack Flash"] }]
this.songs = [];
}
</script>
<body ng:controller="MyController">
<p>selected: <span ng:bind="selected" ng:init="selected='none'" /></p>
<ul>
<li ng:repeat="artist in list">
<button ng:click="selected = artist.name" >{{artist.name}}</button>
</li>
</ul>
<!--ol>
<li ng:repeat="song in songs">
{{song}}
</li>
</ol-->
</body>
我想动态显示被点击艺术家的歌曲列表。这是正确的方法吗?
最佳答案
问题是,ng:repeat
创建了新的作用域,因此您在当前作用域中设置了 selected
,但跨度绑定(bind)到父作用域。
有多种解决方案,定义一个方法可能是最好的:
<div ng:controller="MyController">
<p>selected: {{selected.name}}</p>
<ul>
<li ng:repeat="artist in list">
<button ng:click="select(artist)" >{{artist.name}}</button>
</li>
</ul>
</div>
和 Controller :
function MyController() {
var scope = this;
scope.select = function(artist) {
scope.selected = artist;
};
scope.list = [{
name: "Beatles",
songs: ["Yellow Submarine", "Helter Skelter", "Lucy in the Sky with Diamonds"]
}, {
name: "Rolling Stones",
songs: ["Ruby Tuesday", "Satisfaction", "Jumpin' Jack Flash"]
}];
}
这是您在 jsfiddle 上工作的示例:http://jsfiddle.net/vojtajina/ugnkH/2/
关于javascript - Angularjs 从列表中单击并显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9399239/