ページで次のコントローラーとディレクティブを定義しています。
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);
}
これを行うためにコードを変更するにはどうすればよいですか?