我在服务中保留了一个数据模型,以便各种控制器可以使用它们。在控制器内部,我对它进行了限定,以便元素可以使用 ng-model 绑定到它:
在控制器中:
angular.module('hiveApp').controller('weatherController', function($scope, $rootScope, weatherModel, messageService, utilityService, $http, $timeout, $cookies, $window, $controller) {
$scope.weatherModel = weatherModel;
然后在 HTML 元素中:
<input type="text" id="city" ng-model="weatherModel.city" />
到目前为止一切顺利,这行得通。当我将指令带入组合时,就会出现问题。我有一个处理一对单选按钮并使用模板的指令。该模板尝试使用 ng-model 来引用相同的 weatherModel 服务参数,但是虽然它在页面本身的 HTML 中工作,但指令模板不起作用:
app.directive('radiopair', function() {
return {
restrict: 'E',
template: `
<div style="color:white; float:left">
<input type="radio" id="metric" name="conversion" value="metric"
ng-model="weatherModel.conversion" selected> Metric<br>
<input type="radio" id="imperial" name="conversion" value="imperial"
ng-model="weatherModel.conversion"> Imperial<br>
</div>
`,
link: function ($scope, element, attrs) {
element.on('click', function (event) {
event.currentTarget.selected = true;
$scope.refreshTable();
});
}
}
});
当我在两个按钮之间切换时, ng-model=weatherModel.conversion 值永远不会更新。我认为这必须是一些范围界定问题,但我正在碰壁如何解决它。