我正在创建一个自定义下拉菜单。我设法让指令代码取代它。如何将值绑定到angularjs指令?
下面是在html
<dropdown placeholder="Country.." list="count" selected="item" property="name"></dropdown>
下面的指令标签HTML模板替换指令标签
<div class="dropdown-container" ng-class="{ show: listVisible }">
<div class="dropdown-list">
<div>
<div ng-repeat="item in list" ng-click="select(item)" ng-class="{ selected: isSelected(item) }">
<span>{{property !== undefined ? item[property] : item}}</span>
<i class="fa fa-check"></i>
</div>
</div>
</div>
下面是angularjs指令
App.directive("dropdown", function ($rootScope) {
return {
restrict: "E",
templateUrl: "/app/dropdownTemplate.html",
scope: {
placeholder: "@",
list: "=",
selected: "=",
property: "@"
},
link: function (scope) {
scope.listVisible = false;
scope.isPlaceholder = true;
scope.select = function (item) {
scope.isPlaceholder = false;
scope.selected = item;
};
scope.isSelected = function (item) {
return item[scope.property] === scope.selected[scope.property];
};
scope.show = function() {
scope.listVisible = true;
};
$rootScope.$on("documentClicked", function (inner, target) {
console.log($(target[0]).is(".dropdown-display.clicked") || $(target[0]).parents(".dropdown-display.clicked").length > 0);
if (!$(target[0]).is(".dropdown-display.clicked") && !$(target[0]).parents(".dropdown-display.clicked").length > 0)
scope.$apply(function() {
scope.listVisible = false;
});
});
scope.$watch("selected", function (value) {
scope.isPlaceholder = scope.selected[scope.property] === undefined;
scope.display = scope.selected[scope.property];
});
}
}
});
我想从另一个控制器,其功能如下得到国家的名单,
addressService.getCountries().success(function (response) {
angular.copy(response, $scope.list);
}
如何绑定从控制器到我的指令,在页面加载时的值?
编辑:我该怎么做,因为指令加载功能addressService.getCountries()
被调用之前加载?
只需绑定列表使用双向绑定('=')将'scope.list'指向'scope {}'中的另一个属性? –
使用服务传递数据 – Kailas
@NexusDuck请您详细说明一下吗?我无法理解怎么加属性'范围{}' – Rai