![](/img/trans.png)
[英]How To Watch a JQuery Selector Using AngularJS scope.$watch() Method
[英]Using $watch method in AngularJS
我正在关注亚当·弗里曼(Adam Freeman)的书“ Pro AngularJS”。 但是我停留在清单15-10中。 他提供的代码根本不起作用。
演示代码如下。 它应该以以下方式工作:当我们单击按钮来修改价格时,此列表必须自动更新。 您能让我知道如何修正他的代码吗? 我已经用谷歌搜索了很多,但是....
<!doctype html>
<html ng-app="exampleApp">
<head>
<script src="angular.js"></script>
<link rel="stylesheet" href="bootstrap.css"/>
<link rel="stylesheet" href="bootstrap-theme.css"/>
<script>
angular.module("exampleApp", [])
.controller('defaultCtrl', function ($scope) {
$scope.products = [
{name: "Apples", category: "Fruit", price: 1.20, expiry: 10},
{name: "Bananas", category: "Fruit", price: 2.42, expiry: 7},
{name: "Pears", category: "Fruit", price: 2.02, expiry: 6}
];
$scope.incrementPrices = function(){
for(var i=0; i< $scope.products.length; i++){
$scope.products[i].price += 1;
}
}
})
.directive("unorderedList", function () {
return function (scope, element, attrs) {
var data = scope[attrs["unorderedList"]];
var propertyExpression = attrs["listProperty"];
if (angular.isArray(data)) {
var listElem = angular.element("<ul>");
element.append(listElem);
for (var i = 0; i < data.length; i++) {
var itemElement = angular.element('<li>');
listElem.append(itemElement);
var watcherFn = function (watchScope) {
return watchScope.$eval(propertyExpression, data[i]);
}
scope.$watch(watcherFn, function (newValue, oldValue) {
itemElement.text(newValue);
});
}
}
}
})
</script>
</head>
<body ng-controller="defaultCtrl">
<div class="panel panel-default">
<div class="panel-heading">
<h3>Products</h3>
</div>
<div class="panel-body">
<button class="btn btn-primary" ng-click="incrementPrices()">Change prices</button>
</div>
<div class="panel-body">
<div unordered-list="products" list-property="price | currency"></div>
</div>
</div>
</body>
</html>
继续阅读,在下一个捕获15-11中,他们将告诉您先前的代码无效。
If you load the directives.html file into the browser, the directive won’t keep the li elements up-to-date. If you look
at the HTML elements in the DOM, you will see that the li elements don’t contain any content. This is a problem that
is so common that I want to demonstrate how to fix it even though it results from a JavaScript, rather than AngularJS,
feature.
这是15-11中的代码,其中添加了函数闭包http://jsbin.com/ducihibahi/1/edit?html,输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.