我刚刚接手了 AngularJS 应用程序的前端工作,但我陷入了困境。
我一直在创建指令来替换臃肿的 html,以使更新前端看起来更容易。一切都很顺利,直到我进入我们的选举应用程序的投票页面。
指令传递参数(无效)
<div block-container header="vm.electionToVote.name" startrow="'false'">
<div block-container header="'vm.electionToVote.name'" startrow="'false'">
<div block-container header="{{vm.electionToVote.name}}" startrow="'false'">
通常这些工作
<div block-container header="'Elections List'">
<div block-container header="vm.full.title" startrow="'false'">
指令 html <h3>{{style.header}}</h3>
指令
.directive('blockContainer', blockContainer);
/* @ngInject */
function blockContainer() {
var directive = {
scope: {
header: '=',
startrow: '='
},
replace: true,
transclude: true,
controller: blockContainerCtrl,
controllerAs: 'style',
templateUrl: 'app/style/directives/blockContainer.tpl.html',
restrict: 'A'
};
return directive;
function blockContainerCtrl($scope) {
//debugger;
var vm = this;
vm.header = $scope.header;
vm.startrow = angular.isDefined($scope.startrow) ? $scope.startrow : 'true';
}
}
运行调试显示 vm.electionToVote 未定义,但 ng-inspector 显示它有内容(id、名称、endDate 等)屏幕截图:/image/lXn5U.png
您可以在此处查看所有(包括选举)文件:https://plnkr.co/edit/bPVp8QY0xzlJ6aWZoRDi?p=preview
我确实是一个 angualjs 初学者,但是通过 google、stackoverflow 和大量的试验和错误,我正在完成工作......有点......
任何其他提示/建议也将不胜感激
最佳答案
由于您已在 HTML 上使用 style.header
来绑定(bind) HTML 上的 header
值,因此您应该在指令中添加 bindToController: true
,以便所有独立的作用域绑定(bind)都将在您的指令 html 中可用。
指令
var directive = {
scope: {
header: '=',
startrow : '='
},
replace: true,
transclude: true,
controller: blockContainerCtrl,
controllerAs: 'style',
templateUrl: 'app/style/directives/blockContainer.tpl.html',
restrict: 'A',
bindToController: true //<-- Added this line
};
指令用法
<div block-container header="vm.electionToVote.name" startrow="'false'">
此外,您不应该在 Controller 内手动进行 header
和 startrow
变量赋值。删除这两个分配部分将使其工作。
关于javascript - 无法将动态参数传递给 Angular Directive(指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42036323/