答案 0 :(得分:0)
您可以使用附加到所有(function() {
'use strict';
angular
.module('app', [])
.controller('itemController', itemController)
.controller('sectionController', sectionController)
.factory('SectionService', SectionService);
sectionController.$inject = ['$scope'];
function itemController($scope) {
var vm = this;
vm.change = change;
vm.items = [
{
"id":1,
"name":"Item1"
},
{
"id":2,
"name":"Item2"
},
{
"id":3,
"name":"Item3"
}
];
function change(id) {
// send data to child controller
$scope.$broadcast('id', id);
}
}
sectionController.$inject = ['SectionService', '$scope'];
function sectionController(SectionService, $scope) {
var store = this;
var id = 1;
// It's only to work here...
var fakeData = [
{
"name":"Section1",
"itemID":1,
"sectionID":1
},
{
"name":"Section2",
"itemID":1,
"sectionID":2
},
{
"name":"Section3",
"itemID":1,
"sectionID":3
},
{
"name":"Section4",
"itemID":1,
"sectionID":4
}
];
function getSuccess(response) {
// store.sections = response.data; <- it should be uncommented in your real application
store.sections = fakeData;
}
function getError(response) {
console.log(response);
}
// get the broadcast
$scope.$on('id', function(event, id) {
if (!id) return;
getSuccess();
/*SectionService.getSections(id)
.then(getSuccess)
.catch(getError); <- it should be uncommented in your real application */
})
}
SectionService.$inject = ['$http'];
function SectionService($http) {
var factory = {
getSections: getSections
}
return factory;
function getSections(id) {
//return $http.get('url' + id); <- it should be uncommented in your real application
}
}
})();
元素的<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
<div class="form-group" ng-controller="itemController as item">
<select class="form-control" ng-model="itemForm.item" ng-options="item.name for item in item.items track by item.id" ng-change="item.change(itemForm.item.id)" required>
<option value="" label="Select item" hidden>
</select>
<hr>
<div ng-controller="sectionController as section">
<p ng-repeat="section in section.sections" ng-bind="section.name"></p>
</div>
</div>
</body>
</html>
事件,将每个change
元素的<select>
设置为当前selectedIndex
select
元素change
利用event.target
排除当前元素selectedIndex
,.each()
this
.not()