本文主要展示怎样用directives实现buttons radio,直接上代码
<link href="../bootstrap.css" rel="stylesheet"/>
<script type="text/javascript" src="../jquery.js"></script>
<script type="text/javascript" src="../bootstrap.js"></script>
<script type="text/javascript" src="../angular.js"></script>
<script type="text/javascript" src="buttons-radio-controller.js"></script>
<div class="span6">
<br>
<strong>myModel: </strong>
<code> {{myModel}} </code>
<hr>
<div>
<input name="test" type="radio" ng-model='myModel' value="Left"> Left<br>
<input name="test" type="radio" ng-model='myModel' value="Middle"> Middle<br>
<input name="test" type="radio" ng-model='myModel' value="Right"> Right<br>
</div>
<hr>
<buttons-radio class="btn-group" data-toggle="buttons-radio" model='myModel' options='myOptions'></buttons-radio>
</div>
$scope.myOptions = ["Left", "Middle", "Right"];
$scope.myModel = "Left"
$scope.$watch('myModel', function(v){
console.log('changed', v);
});
.directive('buttonsRadio', function() {
return {
restrict: 'E',
scope: { model: '=', options:'='},
controller: function($scope){
$scope.activate = function(option){
$scope.model = option;
};
},
template: "<button type='button' class='btn' "+
"ng-class='{active: option == model}'"+
"ng-repeat='option in options' "+
"ng-click='activate(option)'>{{option}} "+
"</button>"
};
});
scope:一般用于从controller中获取$scope中的一些值
![编写 <wbr>buttonsRadio <wbr>directivies 编写 <wbr>buttonsRadio <wbr>directivies](https://i-blog.csdnimg.cn/blog_migrate/246050728166ff0613208bb8f23eeb9e.gif)
buttons-radio.html
<!doctype html>
<html lang="en" ng-app="buttonsRadio">
<head>
</head>
<body ng-controller="MainCtrl">
<div class="container">
</div>
</body>
</html>
buttons-radio-controller.js
"use strict";
function MainCtrl($scope) {
}
angular.module('buttonsRadio', [])
测试本代码时,注意将引入的resources放到上级目录,或更改html中resouces的location。
对buttonsRadio directives的解释:
restrict
:
代码中我们使用了"E"属性,表示创建此directive将创建一个element