【腾讯云】云产品限时秒杀,爆款1核2G云服务器,首年99元

初学angular-简单的angular指令

实现一个简单的input清空内容,且清空对应ngModel

前台部分

<html ng-app="hpapp">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="css/test.css">
    <script type="text/javascript" src="js/angular.js"></script>
    <script type="text/javascript" src="js/inputempty.js"></script>
    <script type="text/javascript" src="js/info.js"></script>
</head>

<body>
    <div ng-controller="InfoCtrl">
        <input type="text" name="email" ng-model="model.email" inputempty maxvalue="10">
        <br>
        <br>
        <br>
        <input type="text" name="text" ng-model="model.text" inputempty>
        <br>
        <br>
        <br> {{model.email +"*"+ model.text}}
    </div>
</body>

</html>

控制器部分  info.js

1 var app = angular.module('hpapp');
2 app.controller('InfoCtrl', function($scope) {
3     $scope.model = {
4         email: '1073520680',
5         text: ''
6     };
7 });

指令部分

var app = angular.module('hpapp', []);
app.directive('inputempty', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            var close = '<span class="clear"></span>';
            elem.next().bind('click', function() {
                ctrl.$setViewValue('');
                ctrl.$render();
            });
        }

    };
});
ctrl.$setViewValue('');//清空ngModel
elem.val('');//清空表单

css 部分

.closeW{
    width: 16px;
    height: 16px;
    color: #ccc;
    text-align: center;
    line-height: 16px;
    border: 1px solid #ccc;
    border-radius:16px;
    float: left;
}
.content{
    width: 530px;
    border:1px solid #ccc;
    position: relative;
}
.editW{
    width: 480px;
    min-height: 280px;
    margin: 0;
    padding: 10px;
    outline: none;
}
.clear{
    clear: both;
}
.empty{
    width: 16px;
    height: 16px;
    color: #ccc;
    text-align: center;
    line-height: 16px;
    border-radius:16px;
    border: 1px solid #ccc;
    margin-left: -20px;    
    cursor: pointer;
    display: inline-block;
}

.clear {
    display: inline-block;
    width: 20px;
    height: 20px;
    position: absolute;
    margin-left: -20px;
    cursor: pointer;
    background: url('http://fanyi.baidu.com/static/i18n/zh/widget/translate/main/translateio/clear_9154fd87.png') no-repeat -20px -10px;
}

input{
    padding-right:20px;
    padding-left: 5px;
}

 

posted @ 2016-01-19 09:42  happenzh  阅读(186)  评论(0编辑  收藏  举报