文件结构如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="angular.min.js"></script>
</head>
<body ng-app="app" ng-controller="c">
<div ng-include="'s1.html'"></div>
<script src="s1.js"></script>
</body>
</html>
s1.html
<div>
<select ng-model="datasource"
ng-change="changeDs()"
ng-options="d as d.sourceName+' ('+d.sourceType+')' for d in datasourceList"></select>
</div>
s1.js
var app = angular.module('app', []);
app.controller('c', function($scope) {
$scope.changeDs = function() {
console.log($scope.datasource);
};
});
在changeDs事件中,datasource的值始终为空。因为ng-include指令会创建新的作用域,导致父页面无法找到ng-model绑定的值。
解决方法:加上$parent
<div>
<select ng-model="$parent.datasource"
ng-change="changeDs()"
ng-options="d as d.sourceName+' ('+d.sourceType+')' for d in datasourceList"></select>
</div>