AngularJS指令显示元素文本内容

时间:2016-11-22 18:23:59

标签: angularjs angularjs-directive

我想创建一个可以访问元素文本内容的AngularJS元素指令。例如,我想创建一个我可以这样使用的指令:

<my-text-input g-model="something" g-placeholder="Enter some text">My label</my-text-input>

如何访问上面的My label文字? 我创建了以下示例:

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>AngularJS Element</title>
    <!-- AngularJS -->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>

</head>
<body ng-app="myApp">

<div ng-controller="MyCtrl">
    <h1>Directive Example</h1>
    <my-text-input g-label="My label" g-model="something" g-placeholder="Enter some text"></my-text-input>
    <br>
    <!-- I really want to use it like this: -->
    <my-text-input g-model="something" g-placeholder="Enter some text">My label</my-text-input>
    <p>Text value: {{something}}</p>
</div>

<script>
    var app = angular.module('myApp',[]);

    app.controller('MyCtrl', ['$scope', function($scope) {
        $scope.something= "Example"
    }]);

    app.directive('myTextInput',function(){
        return {
            restrict: 'E',
            template: '<div>' +
            '<label>{{gLabel}}</label> ' +
            '<input ng-model="gModel" type="text" placeholder="{{gPlaceholder}}">' +
            '</div>',
            scope: {
                gLabel : "@",
                gModel : "=",
                gPlaceholder : "@?"
            }
        };
    });

</script>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

所以看起来这正是ng-transclude的用途。我更新了我的例子:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>AngularJS Element</title>
    <!-- AngularJS -->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
</head>
<body ng-app="myApp">

<div ng-controller="MyCtrl">
    <h1>Directive Example</h1>
    <my-text-input g-model="something" g-placeholder="Enter some text">My label</my-text-input>
    <p>Text value: {{something}}</p>
</div>

<script>
    var app = angular.module('myApp',[]);

    app.controller('MyCtrl', ['$scope', function($scope) {
        $scope.something= "Example"
    }]);

    app.directive('myTextInput',function(){
        return {
            restrict: 'E',
            transclude : true,
            template: '<div>' +
            '<label ng-transclude></label> ' +
            '<input ng-model="gModel" type="text" placeholder="{{gPlaceholder}}">' +
            '</div>',
            scope: {
                gModel : "=",
                gPlaceholder : "@?"
            }
        };
    });

</script>
</body>
</html>