由于某种原因,我的指令中的链接函数没有被调用。我可以看到我的指令是通过 console.log 调用的,但不是链接函数。另外,不要介意 Controller 参数,我将在我的父指令中使用它。我也尝试过 limit: 'E' 但也没有运气。我没有在这个例子中使用它。不确定是什么导致它跳过链接。有什么想法吗?
module FormTest {
angular
.module('FormTest') //Gets the FormTest Module
.directive('jiTab', function () {
console.log('directive was hit');
function linkFn(scope, ele, attrs, controller) {
console.log('Link is called');
};
return {
require: '^ji-Tabset',
restrict: 'C',
transclude: true,
link: linkFn
}
});
}
HTML
<ji-form name="Main Form">
<ji-tabset name="Tabs">
<ji-tab tab-name="General"></ji-tab>
<ji-tab tab-name="Stats"></ji-tab>
</ji-tabset>
</ji-form>
家长指令
module FormTest {
angular
.module('FormTest') //Gets the FormTest Module
.directive('jiTabset', function () {
return {
restrict: 'E',
transclude: true,
replace: true,
templateUrl: 'FormTest/views/ji-Tabset.html',
controller: function ($scope) {
var tabPanelItems = $scope.tabPanelItems = [];
$scope.tabSettings = {
dataSource: tabPanelItems
}
}
};
});
}
最佳答案
module FormTest {
angular
.module('FormTest') //Gets the FormTest Module
.directive('jiTab', function () {
console.log('directive was hit');
function linkFn(scope, ele, attrs, controller) {
console.log('Link is called');
};
return {
require: '^ji-Tabset', //<-- this must be `^jiTabset` read mistake 1
restrict: 'C', //<-- this must be `E` which stands for element, (jiTab) C is for class, read mistake 2
transclude: true,
link: linkFn
}
});
}
来自文档
错误1
标准化 Angular 规范化元素的标签和属性名称,以确定哪些元素与哪些指令匹配。我们通常通过区分大小写的驼峰式规范化名称(例如 ngModel)来引用指令。但是,由于 HTML 不区分大小写,因此我们通过小写形式引用 DOM 中的指令,通常在 DOM 元素上使用破折号分隔的属性(例如 ng-model)。
规范化过程如下:
- 从元素/属性的前面删除 x- 和 data-。
- 将 :、- 或 _ 分隔的名称转换为驼峰式命名法。
错误2
限制选项通常设置为:
- 'A' - 仅匹配属性名称
- 'E' - 仅匹配元素名称
- 'C' - 只匹配类名 这些限制都可以根据需要组合起来:
'AEC' - 匹配属性或元素或类名称
错误3
您的 jiTabset
指令中没有 ng-transclude
属性,请确保其中有它 'FormTest/views/ji-Tabset.html'
Worknig 演示
打开浏览器控制台
angular.module('FormTest', []);
angular.module('FormTest') //Gets the FormTest Module
.directive('jiTabset', function () {
return {
restrict: 'E',
transclude: true,
replace: true,
template: '<div>ji-tabset<div ng-transclude></div></div>',
controller: function ($scope) {
var tabPanelItems = $scope.tabPanelItems = [];
$scope.tabSettings = {
dataSource: tabPanelItems
}
}
};
});
angular.module('FormTest') //Gets the FormTest Module
.directive('jiTab', function () {
function linkFn(scope, ele, attrs, controller) {
console.log('Link is called');
};
return {
require: '^jiTabset',
restrict: 'E',
transclude: true,
link: linkFn
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>
<div ng-app="FormTest">
<ji-form name="Main Form">
<ji-tabset name="Tabs">
<ji-tab tab-name="General"></ji-tab>
<ji-tab tab-name="Stats"></ji-tab>
</ji-tabset>
</ji-form>
</div>
关于AngularJS Link 函数没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32229005/