【发布时间】:2015-07-11 21:17:19
【问题描述】:
我正在开发一个具有两种状态的 Angular 应用程序:home 和 lists。
“主页”视图具有创建“列表”的表单,并显示已创建的“列表”。
“列表”视图根据参数 ID(例如 #/lists0、#/lists1、#/lists2 等)显示特定列表的内容。
我正在尝试根据选择框的值将选定的列表内容显示在“主页”视图上。
这是我目前所拥有的,
js/app.js
angular.module('d-angular', ['ui.router'])
// Set routing/configuration
// ------------------------------
.config(['$stateProvider', '$urlRouterProvider',
// Set state providers
function($stateProvider, $urlRouterProvider) {$stateProvider
// Home state
.state('home', {
url: '/home',
templateUrl: '/static/home.html',
controller: 'MainCtrl'
})
// Lists state
.state('lists', {
url: '/lists{id}',
templateUrl: '/static/lists.html',
controller: 'ListsCtrl'
})
$urlRouterProvider.otherwise('home');
}
])
// lists factory
// Factories are used to organize and share code across the app.
// ------------------------------
.factory('lists', [function(){
// create new obect with array of lists
var o = { lists: [] };
return o;
}])
// Main controller
// ------------------------------
.controller('MainCtrl', ['$scope', 'lists',
// Main scope (used in views)
function($scope, lists){
// array of lists
$scope.lists = lists.lists;
// Add list function
$scope.addList = function(){
// prevent empty titles
if(!$scope.title || $scope.title === '') {
return;
}
// push new list to array
$scope.lists.push({
title: $scope.title,
date: new Date().toJSON().slice(0,10),
words: [
// add default words
{ title: "no", date: new Date().toJSON().slice(0,10) },
{ title: "yes", date: new Date().toJSON().slice(0,10) }
]
});
// reset title
$scope.title = '';
};
}
])
// Lists controller
// ------------------------------
.controller('ListsCtrl', ['$scope', '$stateParams', 'lists', '$http',
// Main scope (used in views)
function($scope, $stateParams, lists, $http){
// get list by ID
$scope.list = lists.lists[$stateParams.id];
// Add comment function
$scope.addWord = function(){
// push new list to array
$scope.list.words.push({
title: $scope.title,
date: new Date().toJSON().slice(0,10)
});
};
}
]);
静态/home.html
<div class="page-header">
<h1>Lists</h1>
</div>
<!-- add a list -->
<form ng-submit="addList()">
<input type="text" ng-model="title"></input>
<button type="submit">Add</button>
</form>
<!-- end add -->
<!-- list all lists -->
<select ng-model="lists" ng-options="list.id as list.title for list in lists">
<option value="">Select List</option>
</select>
<!-- end list -->
<!-- list words in selected list -->
<div ng-repeat="list in lists{{$index}}">
<div ng-repeat="word in list.words">
{{ word.title }} <br>
{{ word.date }}
</div>
<hr>
</div>
<!-- end words -->
我不确定如何从选择框中获取特定的 ID 值并使用它来显示特定的列表内容。
感谢任何帮助。
【问题讨论】:
-
具体出了什么问题?
-
我不确定如何从选择框中传输 ID 值以呈现特定列表中的单词。上面的代码没有出现任何错误,但是当我选择一个值时,列表中没有任何内容呈现
-
你能复制到你的列表控制器吗?
标签: javascript angularjs single-page-application