我使用角度js制作了一个基本的自定义指令。我可以将范围记录到控制台,但它不会在标记内显示模板。我正在摆弄继承,共享和隔离的范围,并想知道我的指令是否错误嵌套?
var myApp = angular.module('myApp', []);
myApp.controller('StudentController', ['$scope', function ($scope) {
$scope.student = {
name: "dj",
age: 32,
subject: [
"math",
"geography"
]
}
$scope.setGrade = function (student) {
student.grade = "A+"
}
//console.log($scope.student);
myApp.directive('studentDir',function(){
return{
template:"{{student.age}} years old!",
replace: true,
restrict: 'E',
controller: function($scope){
//console.log($scope);
}
}
});
}]);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="StudentController">
<student-dir></student-dir>
</div>
</body>
&#13;
答案 0 :(得分:0)
从指令中删除replace: true
将使其正常工作。因为当您使用replace: true
时(虽然已经弃用),您必须在template
中单个DOM元素,因为$compile
服务只需要单个根来编译。但是这里有{{student.age}} years old!
个DOM节点。
或者使用span
/ div
template:"<span>{{student.age}} years old!</span>",
答案 1 :(得分:0)
另一种解决方案是使用<div>
return {
template:"<div>{{student.age}} years old!</div>",
replace: true,
restrict: 'E',
controller: function($scope){
//console.log($scope);
}
}
修改强>
如果您的代码与上面发布的代码相同,那么您需要在控制器之外声明您的指令,如下所示:
var myApp = angular.module('myApp', []);
myApp.controller('StudentController', ['$scope', function ($scope) {
$scope.student = {
name: "dj",
age: 32,
subject: [
"math",
"geography"
]
}
$scope.setGrade = function (student) {
student.grade = "A+"
}
}]);
myApp.directive('studentDir',function(){
return{
template:"<div>{{student.age}} years old!</div>",
replace: true,
restrict: 'E',
controller: function($scope){
//console.log($scope);
}
}
});