使用angularjs指令编译文本框

时间:2015-08-12 12:57:03

标签: angularjs angularjs-directive

我想在angularjs中使用指令编译文本框 像自定义文本框。谁能帮我?
当我试图用拖曳论证来编译第1行文本框时,这是个问题。
提前致谢。
见第1行-----------
这是教程点示例我改变了一些内容。

<div ng-app="mainApp" ng-controller="StudentController">
    <student name="Mahesh"></student><br/>
    <student name="Piyush"></student>
</div>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
    var mainApp = angular.module("mainApp", []);

    mainApp.directive('student', function() {
        var directive = {};
        directive.restrict = 'E';
        directive.template = "Student: <b>{{student.name}}</b> , Roll No: <b>{{student.rollno}} </b> <br/> <input name='{{student.mytype}}' type='{{student.mytype}}'> ";

        directive.scope = {
            student : "=name"
        }

        directive.compile = function(element, attributes) {
            // element.css("border", "1px solid #cccccc");

            var linkFunction = function($scope, element, attributes) {
                element.html("Student: <b>"+$scope.student.name +"</b> , Roll No: <b>"+$scope.student.rollno+"</b><br/>" +
                "<b> <input type='"+$scope.student.mytype+"' name='+$scope.student.mytype+'  > "); -----line 1
                //element.css("background-color", "#ff00ff");
            }

            return linkFunction;
        }

        return directive;
    });

    mainApp.controller('StudentController', function($scope) {
        $scope.Mahesh = {};
        $scope.Mahesh.name = "Mahesh Parashar";
        $scope.Mahesh.rollno  = 1;
        $scope.Mahesh.mytype = "email";

        $scope.Piyush = {};
        $scope.Piyush.name = "Piyush Parashar";
        $scope.Piyush.rollno  = 2;
        $scope.Piyush.mytype = "password";
    });
</script>

1 个答案:

答案 0 :(得分:2)

我刚刚更新了以下代码。问题出在 b 标记上,您没有关闭它,也忘了在name属性中添加双引号。

var linkFunction = function($scope, element, attributes) {
        element.html("Student: <b>"+$scope.student.name +"</b> , Roll No: <b>"+$scope.student.rollno+"</b><br/>" +
        "<b> <input type='"+$scope.student.mytype+"' name='"+$scope.student.mytype+"'  /></b> ");

}