我编写了一个简单的AngularDart应用程序来查询Web服务。用户在搜索框中输入文本,搜索框中的每个新字符都会向Web服务触发查询。这很好。
但是,我想在返回请求后更新视图。这不起作用。收到结果(我可以将其打印到控制台)。但结果(产品列表)不会呈现给显示器。
当我得到结果时,如何从控制器更新视图?
以下是main.dart文件:
library products;
import 'package:angular/angular.dart';
import 'package:angular/application_factory.dart';
import 'dart:html';
import 'dart:convert';
class MyAppModule extends Module {
MyAppModule() {
type(ProductController);
}
}
void main() {
applicationFactory()
.addModule(new MyAppModule())
.run();
/* Listen to the search box */
querySelector('#searchBox').onInput.listen(startQuery);
}
void startQuery(Event e) {
String queryText = (e.target as InputElement).value;
ProductController.query(queryText);
}
final String SERVER_URL = "http://127.0.0.1:3000/query/";
@Controller(
selector: '[products]',
publishAs: 'prods')
class ProductController {
static List<Product> _products;
ProductController() {
_products = [];
/* This is only for testing, this works */
query('beer');
}
static void query(String query) {
String url = SERVER_URL + query;
var request = HttpRequest.getString(url).then(_onDataLoaded);
}
/* When the query result returns, this is run */
static void _onDataLoaded(String responseText) {
Map responseJSON = JSON.decode(responseText);
_products = _getProductList(responseJSON['results']);
/* This fire always, even when user enters text */
print(_products);
}
/* Convert the Map to a Product List */
static List<Product> _getProductList(List<Map> productMapList) {
List<Product> list = [];
for (var objProduct in productMapList) {
list.add(new Product.fromObject(objProduct));
}
return list;
}
List<Product> get products => _products;
}
class Product {
String name;
String company;
Product.fromObject(var objProduct) {
name = objProduct['name'];
company = objProduct['company'];
}
}
以下是html文件的正文:
<body>
<!-- The Search Area -->
<div search-area class="search-area">
<div class="col span_1_of_3"></div>
<div class="col span_1_of_3">
<input type="text" name="name" id="searchBox" placeholder="Search" autocomplete="off" tabindex="1">
</div>
<div class="col span_1_of_3"></div>
</div>
<!-- The Results Area -->
<div products class="results-area">
<div ng-repeat="product in prods.products">
<!-- List all products -->
<div class="col span_1_of_3">
{{product.name}}
</div>
</div>
</div>
<script src="packages/shadow_dom/shadow_dom.min.js"></script>
<script type="application/dart" src="myapp.dart"></script>
<script type="text/javascript" src="packages/browser/dart.js"></script>
</body>
答案 0 :(得分:0)
答案很简单。
ProductController() {
_products = [];
/* This is only for testing, this works */
query('beer');
/* This Code is new: this can be init'd here instead of in main */
querySelector('#searchBox').onInput.listen(startQuery);
}
原因是AngularDart在其范围内保存了ProductController对象,之前我创建了一个新的ProductController对象,它在范围之外,因此更改未更新到视图。