我的页面中定义了以下控制器和指令:
var pof = angular.module('pof', []);
pof.controller("Main", function($scope, $rootScope) {
$scope.services = [{
id: 1,
name: "service1"
}, {
id: 2,
name: "service2"
}, {
id: 3,
name: "service3"
}, {
id: 4,
name: "service4"
}, {
id: 5,
name: "service5"
}];
// I want to call this when an item is selected from the dropdown
// and I want to be able to access the name of the selected item
$scope.selectService = function(service) {
console.log("service:" + service.name);
}
});
pof.directive('bsDropdown', function($compile) {
return {
restrict: 'E',
scope: {
items: '=dropdownData',
doSelect: '&selectVal',
selectedItem: '=preselectedItem'
},
link: function(scope, element, attrs) {
var html = '<div class="btn-group"><button class="btn button-label btn-info">Choose a service</button><button class="btn btn-info dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button><ul class="dropdown-menu"><li ng-repeat="item in items"><a tabindex="-1" data-ng-click="selectVal(item)">{{item.name}}</a></li></ul></div>';
element.append($compile(html)(scope));
for (var i = 0; i < scope.items.length; i++) {
if (scope.items[i].id === scope.selectedItem) {
scope.bSelectedItem = scope.items[i];
break;
}
}
scope.selectVal = function(item) {
$('button.button-label', element).html(item.name);
scope.doSelect({
selectedVal: item.id
});
};
scope.selectVal(scope.bSelectedItem);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.js"></script>
<script src="https://st.pimg.net/cdn/libs/jquery/1.8/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<body ng-app="pof" ng-controller="Main">
<bs-dropdown data-menu-type="button" select-val="selected_service = selectedVal" preselected-item="selected_service" data-dropdown-data="services">
</bs-dropdown> Selected Value : {{selected_service}}
</body>
当从下拉列表中选择一个选项时, 我希望能够将所选项目传递给控制器中的$scope.selectService()
函数。Main
$scope.selectService = function(service) {
console.log("service:" + service.name);
}
我怎样才能修改我的代码来做到这一点?