[AngularJS]26. !Improtant, Two ways banding and scope to make directive reuseable
In product.js we have an directive like:
app.directive("productReviews", function() {
return {
restrict: 'E',
scope:{
reviewdProduct: "="
},
templateUrl: "product-reviews.html"
};
});
In the code we set scope, name it reviewdProduct :"=" , this is how two ways banding works.
Then we go to product-reviews.html
<!-- Product Reviews List --> <ul> <h4>Reviews</h4> <li ng-repeat="review in reviewdProduct.reviews"> <blockquote> <strong>{{review.stars}} Stars</strong> {{review.body}} <cite class="clearfix" >—{{review.author}}+' on '+{{review.createdOn | date:'MM/dd/yyyy @ h:mma'}}</cite> </blockquote> </li> </ul>
We change
<li ng-repeat="review in product.reviews">
to
<li ng-repeat="review in reviewdProduct.reviews">
We still need to change product-tab.html, because reviewd-product is a custom directive, we need to find it.
<product-reviews reviewd-product="product" ng-show="tab.isSet(3)"></product-reviews>
We add reviewd-product = "product", NOTICE that in Javascript we set 'reviewdProduct', but in HTML we should use 'reviewd-product'
But I haven't finished yet. NOTICE product-tab is also a include html, a directive, therefore we still need to refactor the code here using tow ways banding:
First we change product.js
app.directive("productTabs", function() {
return {
restrict: "E",
scope:{
tabbedProduct: "=" // set scope here also, using two ways banding
},
templateUrl: "product-tabs.html",
controller: function() {
this.tab = 1;
this.isSet = function(checkTab) {
return this.tab === checkTab;
};
this.setTab = function(activeTab) {
this.tab = activeTab;
};
},
controllerAs: "tab"
};
});
Then according to templateUrl we find product-tabs.html, change reviewd-product="product" to reviewd-product="tabbedProduct"
<!-- Review Tab's Content --> <product-reviews reviewd-product="tabbedProduct" ng-show="tab.isSet(3)"></product-reviews>
And index.html as well:
<product-tabs tabbed-product="product"></product-tabs>
For now, the product-tabs can be use everywhere inside the store controller and outside product controller.
<body ng-controller="StoreController as store"> <product-tabs tabbed-product="store.products[x]"></product-tabs> </body>
Those code will also works.
END

浙公网安备 33010602011771号