ras*_*cio 6 javascript angularjs angularjs-controller
我想创建一个简单的列表,当用户点击一个按钮时,该值显示在span元素中.
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>
Run Code Online (Sandbox Code Playgroud)
我想动态显示被点击的艺术家的歌曲列表.这是正确的方法吗?
Voj*_*jta 16
问题是,这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>?
Run Code Online (Sandbox Code Playgroud)
和控制器:
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"]
}];
}?
Run Code Online (Sandbox Code Playgroud)
这是你在jsfiddle上工作的例子:http://jsfiddle.net/vojtajina/ugnkH/2/