我有一个简单的Angular应用程序(只是学习)我试图使用Angular Material。为了使某些内容正常运行,我想使用<md-chips>
将一组属性添加到产品模型中。这是HTML的一个片段:
// EXTRACT FROM VIEW
<md-content class="md-padding" layout="column">
<form name="productForm">
<section class="md-padding" layout="column">
<md-input-container flex>
<label ng-show="productForm.category.$pristine">e.g. Umbrella</label>
<input name="category" ng-model="product.category" ng-minlength="3" ng-maxlength="80" required>
</md-input-container>
</section>
<section class="md-padding" layout="column">
<md-chips ng-model="product.attributes">
<input type="text" placeholder="e.g. Size">
</md-chips>
</section>
</form>
</md-content>
这是JS的一个片段。一切正常 - 除了我希望$scope.productAttrsLen
变量在$scope.$watch('product')
调用中更新。 ProductService.product模型更新....但$scope.productAttrsLen
没有。但是 - 当我还在$scope.$watchCollection
上运行product.attributes
时,$scope.productAttrsLen
会更新。任何人都可以解释为什么,以及我如何在$scope.$watch('product'...)
电话中完成这一切?我评论了下面的代码:
// EXTRACT FROM CONTROLLER
myApp.controller('newProductController', [
'$scope', '$log', 'ProductService',
function (
$scope, $log, ProductService) {
$scope.product = ProductService.product || {};
$scope.product.attributes = [];
function getProductAttsLen() {
return _.size($scope.product.attributes);
}
$scope.productAttrsLen = getProductAttsLen();
// when I only include the following code,
// the product object updates (including the attributes)
// but productAttrsLen does not update.
$scope.$watch('product', function (product) {
ProductService.product = product;
$scope.productAttrsLen = getProductAttsLen();
});
// However, when I ALSO include the following code, the productAttrsLen
// does get updated. Why?? Ideally, it would all get sorted in the
// $scope.$watch('product'...) function call.
$scope.$watchCollection('product.attributes', function (attributes) {
$scope.productAttrsLen = getProductAttsLen();
});
}])