【发布时间】:2025-12-14 17:55:02
【问题描述】:
找不到该指令未运行的原因。 没有任何类型的错误,没有调用链接函数,也没有渲染模板。
原始代码在 TypeScript 上,但我在 plnkr 中重现了完全相同的行为,试图让问题出现,但仍然存在。
Plnkr 版本:http://plnkr.co/edit/vBARsB9PhZ4txjlmolMM?p=preview
JS
angular.module('DirectivesApp', [])
.controller('MainCtrl', ['$scope', function($scope) {
$scope.text = 'find this, also this';
$scope.Items = [{
Key: 'find this',
Value: 'FOUND 1'
}, {
Key: 'also this',
Value: 'FOUND 2'
}];
}]).directive('multiSelect', function() {
return {
templateUrl: 'multipleSelect-template.html',
$scope: {
text: '@text',
Items: '&Items'
},
restrict: 'A',
link: function($scope, element, attrs) {
$scope.text = attrs.text;
}
};
});
HTML
<div ng-app="DirectivesApp">
<div ng-controller="MainCtrl">
<multi-select text="{{text}}" Items="{{Items}}"></multi-select>
</div>
</div>
模板
<input type="text" disabled value="{{text}}" />
<input type="checkbox" ng-repeat="item in Items" value="{{item.Key}}"/><label>{{item.Value}}</label>
PS:尝试制作自定义多选控件。
【问题讨论】:
-
首先要修复的是指令配置属性应该是
scope,而不是$scope~ docs.angularjs.org/api/ng/service/$compile#-scope- -
另外,您使用的
&绑定完全错误。你是不是想使用=Items? -
这里的另一个问题是您的
restrict属性。您将指令用作元素,值应为E -
@PrinceG 这肯定是主要问题 ;)
-
$scope 而不是 scope 是复制错误,谢谢,刚刚修复。现在正在处理绑定和限制。
标签: javascript angularjs angularjs-directive