我想創建一個屬性指令,它將在輸入字段之前插入一個標籤。通過警報聲明判斷,該html看起來是正確的。不過,我沒有正確編譯或做角元素。任何幫助將不勝感激。AngularJS中的屬性指令
的小提琴是http://jsfiddle.net/2suL9/
這是JS代碼。
var myApp = angular.module('myApp', []);
myApp.directive('makeLabel', function ($compile) {
return {
restrict: 'A',
replace: false,
link: function (scope, inputFld, attrs) {
var ForInput = attrs['name'];
var LabelSize = attrs['labelSize'];
var LabelText = attrs['makeLabel'];
var htmlStart = '<label for="' + ForInput + '" class="label-control ' + LabelSize + '">';
var htmlStar = '';
if (attrs['required']) {
htmlStar = '<span style="color:red">*</span>';
}
var htmlEnd = LabelText + ":</label> ";
var htmlTotal = htmlStart + htmlStar + htmlEnd;
alert(htmlTotal);
// Now add it before the input
var newLabel = angular.element(htmlTotal);
inputFld.prepend(($compile(htmlTotal)));
}
};
});
這是HTML
<!DOCTYPE html>
<html class="no-js" data-ng-app="myApp">
<head>
<title></title>
</head>
<body>
<div class="container">
<div class="row">
<form name="TestLabelForm" class="form-horizontal">
<div class="form-group">
<input type="text" name="Simple" required="" make-label="Test Label" label-size="col-md-7" />
</div>
</form>
</div>
<br />
Should look like
<br />
<div class="row">
<form name="ExampleForm" class="form-horizontal">
<div class="form-group">
<label for="Simple2" class="col-md-7"><span style="color:red">*</span>Test Label:</label>
<input type="text" name="Simple2" required="" />
</div>
</form>
</div>
</div>
<!-- Get Javascript -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"> </script>
<script src="js/TestLabelAttr.js"> </script>
</body>
</html>
它適用於我,你期望什麼? – ThomasP1988
「我不編譯或正確執行角度元素」是指? – harishr