编写 buttonsRadio directivies

本文介绍如何使用Angular自定义指令创建按钮样式的单选框组件,并通过实例展示了如何设置选项和监听模型变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文主要展示怎样用directives实现buttons radio,直接上代码编写 <wbr>buttonsRadio <wbr>directivies
buttons-radio.html

<!doctype html>
<html lang="en" ng-app="buttonsRadio">
<head>
    <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>
</head>
<body ng-controller="MainCtrl">
<div class="container">
    <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>
</div>
</body>
</html>

buttons-radio-controller.js

"use strict";

function MainCtrl($scope) {
    $scope.myOptions = ["Left", "Middle", "Right"];
    $scope.myModel = "Left"

    $scope.$watch('myModel', function(v){
        console.log('changed', v);
    });
}

angular.module('buttonsRadio', [])
    .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>"
        };
    });

测试本代码时,注意将引入的resources放到上级目录,或更改html中resouces的location。

对buttonsRadio directives的解释:
restrict代码中我们使用了"E"属性,表示创建此directive将创建一个element
scope:一般用于从controller中获取$scope中的一些值
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值