我对角度相对较新,这是我的第一个参与指令,我有点迷失。我试图在我的应用中的不同标签上创建可重复使用的商品列表。列表的行为相同,但项目的显示方式除外(由单独的部分处理)。我将许多不同类型的属性传递到范围内,并根据我所阅读的内容尝试了几种不同的东西。无论我到目前为止尝试过什么,我仍然遇到属性绑定问题。
以下是我的代码,我会尝试尽可能地解释它,希望有人可以告诉我哪里出错了。唯一看似正确绑定的东西是字符串,缺少对象和函数。
更新:结果我需要将$ scope.currentPage绑定到指令范围。现在ng-repeat正在运行,但页面中需要访问控制器范围的其他部分仍然无法正常工作。我已经更新了以下代码,并继续研究如何授予模板访问权限。
指令
var app = angular.module('main');
app.directive('itemList', function(){
var linkFunction = function(scope, element, attributes){
scope.$watch("query.value", function(){
scope.filterFunction(); //pretty sure this never gets called on search
});
}
return {
restrict: 'E',
replace: 'true',
templateUrl: 'partials/directives/list-tab.html',
link: linkFunction,
scope: {
filterFunction: "&filterFunction",
searchPlaceholder: "@searchPlaceholder",
pagedItems: "=pagedItems",
clickFunction: "&clickFunction",
classString: "@classString",
infoTemplate: "@template",
currentPage: "=currentPage"
}
}
});
的index.html
//pagedCars is an array of nested objects that gets used by the template to display the information
//filterCars is a function
//carSelected is a function
<div class="available-items">
<item-list filter-function="filterCars" search-placeholder="Search Cars" paged-items="pagedCars" current-page="currentPage" click-function="carSelected" class-string="car.carId==selectedCar.carId?'selected':''" template="'partials/cars/cars-template.html'"></item-list>
</div>
列表tab.html
<div class="form-group">
<div class="search-field">
<label for="searchField" id="searchLabel">Search</label><br/>
<input type="text" ng-model="query.value" placeholder="{{searchPlaceholder}}"/>
</div>
<table class="table table-hover>
<tbody>
//currentPage is on the controller scope there's a separate control that allows the user to page through the pagedItems by updating the currentPage which would be reflected here
<tr ng-repeat="item in pagedItems[currentPage]" ng-click="clickFunction($index) ng-class="classString">
<td ng-include="infoTemplate"></td>
</tr>
</tbody>
</table>
</div>
汽车-template.html
<div class="row form-inline" id="{{item.carId}}">
<div class="col-md-2">
//this uses a method on the controller scope to format the url
<img ng-src="{{retrieveIcon(item.iconUrl)}}" height="75px" width="75px"/>
<div class="col-md-10">
<div details-pane" id="carDetails" ng-include="'partials/cars/car-full-details.html'"></div>
<div class="item-title">{{item.name}}</div>
//the rest is just a table with more information about the item. item.description, item.mileage, etc...
</div>
</div>
答案 0 :(得分:1)
尝试使用括号
传递函数<div class="available-items">
<item-list filter-function="filterCars()" search-placeholder="Search Cars" paged-items="pagedCars" click-function="carSelected()" class-string="car.carId==selectedCar.carId?'selected':''" template="'partials/cars/cars-template.html'"></item-list>
</div>
另外,如果您的变量在HTML中的名称与您在指令范围内的名称相同,则可以使用pass方法。 e.g。
scope: {
filterFunction: "&",
searchPlaceholder: "@",
pagedItems: "@",
clickFunction: "&",
classString: "@",
infoTemplate: "@template"
}