我正在尝试做的是有一个服务(比方说: myService),它保存特定的数据,比如表示存在和选择的打印机的对象:
var localPrinters = [{ id: 12, name: 'HP', type: 'laser' },
{ id: 33, name: 'Lexmark', type: 'laser' }];
var activePrinter = {};在一些偶尔显示的视图中(例如应用程序设置),我有一个控制器,它可以在本地范围内定义变量,这些变量将指向注入的myService中的对象。
然后,视图将使用ng-repeat遍历localPrinters中的打印机对象,并显示与数组中的每个对象相对应的单选按钮。
现在我需要两样东西..
1)在单选按钮选择更改时使用相应的对象值更新activePrinter
2)如果activePrinter已经包含一个对象,当视图加载时,我希望相应的单选框已经被选中(如果它的值对象与activePrinter中的对象匹配,否则不应该被选中。
我已经从几个方面设法做到了..要么坚持使用模型,要么添加方法来调用ng-change。
//pseudocode
<container ng-repeat="printer in printers" >
<radio ng-value="printer" ng-model="$scope.activePrinter"/>
</container>或
//pseudocode
<container ng-repeat="printer in printers" >
<radio ng-value="printer" ng-change="selectPrinter(printer)" "ng-model="$scope.activePrinter"/>
</container>我遇到的问题是2)我不确定在angular中是否有一种方法可以自动找出一些打印机的值与activePrinter选择相匹配,并使无线电处于选中状态。我也不确定我是如何使用ng-model实现这个目的的。
有什么建议吗?谢谢!
发布于 2015-03-25 07:11:20
你可以这样做:
var app = angular.module('app', []);
app.controller('firstCtrl', function($scope) {
$scope.printers = [{
id: 12,
name: 'HP',
type: 'laser'
}, {
id: 33,
name: 'Lexmark',
type: 'laser'
}];
$scope.activePrinter = {};
//set default printer
$scope.activePrinter.printer = $scope.printers[0]
});<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="firstCtrl">
<div class="container" ng-repeat="printer in printers">
<label>{{printer.name}}</label>
<input type="radio" ng-value="printer" ng-model="activePrinter.printer" />
</div>
Active Printer:{{activePrinter.printer.id}} | {{activePrinter.printer.name}} | {{activePrinter.printer.type}}
</div>
</body>
https://stackoverflow.com/questions/29243415
复制相似问题