我想创建一个可以访问元素文本内容的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>
&#13;
答案 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>