(function () {
'use strict';
angular
.module('contacts.directives')
.directive('hotkeys', HotkeysDirective);
HotkeysDirective.$inject = ['$resource', '$document'];
function HotkeysDirective($resource, $document) {
var directive = {
templateUrl: '/my-app/contacts/client/views/ui/hotkeys.ui.html',
link: link,
controller: 'AddManagerController',
controllerAs: 'vm',
scope: {},
bindToController: {
},
};
return directive;
function link(scope, element, attrs, modelCtrl) {
$document.bind('keypress', function (e) {
var key = String.fromCharCode(e.which);
if (key == 1 || key == 2 || key == 3 || key == 4 || key == 5 || key == 6) {
scope.$broadcast('keypress', e, e.which);
}
});
scope.$on('keypress', function (event, key) {
// do stuff
scope.$apply();
});
}
}
}());
这是我认为无效的代码......
HotkeysDirective.$inject = ['$resource', '$document'];
function HotkeysDirective($resource, $document) {
var directive = {
templateUrl: '/request-off-work/contacts/client/views/ui/hotkeys.ui.html',
link: link,
controller: 'AddManagerController',
controllerAs: 'vm',
scope: {},
bindToController: {
},
};
return directive;
function link(scope, element, attrs, modelCtrl) {
当我使用controllerAs时,vm未定义:' vm',在AddManagerController中,它表示' var vm = this;'。也不确定为什么范围:{}需要在那里,我最终会弄清楚bindToController ......我想我需要将vm.credentials.groups绑定到它。
更新:这是控制器
function AddManagerController($scope, $document, $rootScope, $state, $window, Authentication, ContactsService, Notification) {
var vm = this;
vm.authentication = Authentication;
vm.credentials = {};
vm.showGroups = [null, false, false, false, false, false, false];
答案 0 :(得分:1)
您不需要使用范围,因为您已绑定到控制器实例this
。
答案 1 :(得分:1)
您定义controller
和controllerAs
等于vm
。然后你想定义一个bindToController = true
,这意味着指令绑定将与控制器相关联。
因此,如果您在控制器内部执行:
this.myVar = 'test';
然后在你的指令模板中你可以做到:
<div>{{vm.myVar}}</div>
答案 2 :(得分:0)
我将指令的link函数中的vm.credentials.groups更改为scope.vm.credentials.groups,现在它可以工作了。希望这个答案可以帮到某个人。