2016-11-22 40 views
1

我想創建一個AngularJS元素指令,它可以訪問元素的文本內容。例如,我想創建一個指示,我可以用這樣的:AngularJS指令顯示元素文本內容

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

我如何才能訪問上述My label文本? 我已經創建了下面的例子:

<!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>

回答

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>