对于 Angular 版本 1.3.4。在以下代码段中,ng-change 事件不起作用。
依赖项: Bootstrap 版本 3.3.0
下面的代码工作到版本 1.2.27
javascript
var app = angular.module("demoApp", ['ngRoute']);
app.controller('DemoController', function ($scope) {
init();
function init() {
$scope.newItemType = 'bill';
$scope.change = function () {
alert($scope.newItemType)
};
}
});
app.config(function ($routeProvider) {
$routeProvider
.when('/prerak/list', {
controller: 'DemoController',
templateUrl: '/app/views/demo.html'
})
});
html
<h4>Demo</h4>
<br />
<div>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-success">
<input type="radio" value="bill" ng-change="change()" ng-model="newItemType"> Insert New Bill <span class="glyphicon glyphicon-file"></span>
</label>
<label class="btn btn-success">
<input type="radio" value="coin" ng-change="change()" ng-model="newItemType"> Insert New Coin <span class="glyphicon glyphicon-adjust"></span>
</label>
</div>
<br/><br/> Selected Item: <b>{{newItemType}}</b>
</div>
以下是 plunkr(更简单的版本):http://plnkr.co/edit/yU9unxI8F6u2ToQzlUV2
最佳答案
当你处理 Angular 时,你不应该依赖 Bootstrap javascript。 Bootstrap 的 jQuery 插件不是为开箱即用的 Angular 量身定制的。如果你想使用 Bootstrap JS,你应该考虑额外的 Angular 模块,比如 AngularUI Bootstrap或 AngularStrap ,它提供了实现相应 Bootstrap 插件功能的专用指令。
以下是 AngularUI Bootstrap 的外观:
<div class="btn-group">
<label class="btn btn-success" btn-radio="'bill'" ng-change="change()" ng-model="newItemType">
Insert New Bill <span class="glyphicon glyphicon-file"></span>
</label>
<label class="btn btn-success" btn-radio="'coin'" ng-change="change()" ng-model="newItemType">
Insert New Coin <span class="glyphicon glyphicon-adjust"></span>
</label>
</div>
请记住在这种情况下声明新的依赖项:
angular.module("demoApp", ['ui.bootstrap'])
这是它的外观
angular.module("demoApp", ['ui.bootstrap']).controller('DemoController', function ($scope) {
$scope.newItemType = 'bill';
$scope.change = function () {
console.log($scope.newItemType)
};
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.0.min.js"></script>
<div class="container" ng-app="demoApp" ng-controller="DemoController">
<h2>Radio Buttons</h2>
<div class="btn-group">
<label class="btn btn-success" btn-radio="'bill'" ng-change="change()" ng-model="newItemType">
Insert New Bill <span class="glyphicon glyphicon-file"></span>
</label>
<label class="btn btn-success" btn-radio="'coin'" ng-change="change()" ng-model="newItemType">
Insert New Coin <span class="glyphicon glyphicon-adjust"></span>
</label>
</div>
<p>Selected Item: <b>{{newItemType}}</b></p>
</div>
演示:http://plnkr.co/edit/pPTir7YGwJKt5L5oxVYX?p=preview
关于angularjs - 自 v1.3.0 起,ng-change,ng-click 不适用于 data-toggle ="buttons",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27897175/