Angularjs单击并从列表中显示
问题描述:
我想创建一个简单列表,当用户单击按钮时,该值将显示在span元素中。Angularjs单击并从列表中显示
HTML &控制器
<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
,但跨度绑定到父范围。
有多种解决方案,定义一个方法可能是最好的:
<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>
而且控制器:
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/
是有办法做到这一点,而不需要在控制器中创建一个方法? – rascio 2012-02-24 15:38:23
是的,你可以,但这种解决方案与控制器方法是恕我直言最好的。 这里是与另外两个解决方案小提琴http://jsfiddle.net/vojtajina/ugnkH/3/ – Vojta 2012-02-26 01:13:43
好吧......作为最后一件事情,看看我是否得到它。在我的文件中,它没有工作,因为我没有在模型中声明“selected”属性,而是在迭代范围内创建它。而在你的第三个例子中,它的工作原理是因为如果它没有在“实际”范围中找到属性,那么在创建它之前它会搜索父范围? – rascio 2012-02-27 14:24:10