如何在链接中访问指令控制器功能?这会返回错误: ReferenceError:未定义getFormatedValue。
看到一些例子,其中一个通过require注入一个单独的控制器,并且能够通过注入它来访问控制器,如下面的代码所示,作为链接函数中的第4个参数。但是,我需要这个控制器在这个指令中。
.directive('testDirective', function () {
link: function ($scope, element, attribute, controller) {
attribute.$observe('numbers', function(value) {
controller.setNumbers(value);
});
attribute.$observe('decimals', function(decimals) {
decimals = decimals || defaultValue();
decimals = (decimals.length > 2 ? decimals.slice(0, 2 - decimals.length) : decimals);
$scope.decimals = controller.getFormatedValue(decimals, 'decimals');
});
},
controller: function ($scope, $element, $attrs) {
this.setNumbers = function (numbers) {
numbers = numbers || $scope.defaultValue();
$scope.numbers = getFormatedValue(numbers, 'numbers');
};
this.getFormatedValue = function(value, kindofvalue){
var maxDecimals = '2',
returnValue;
if (kindofvalue === 'decimals'){
returnValue = addzero(value, maxDecimals);
}
else if (kindofvalue === 'numbers'){
returnValue = value.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
}
return returnValue;
};
this.defaultValue = function() {
return '0';
};
this.addzero = function(decimalValue , maxDecimals) {
return decimalValue.length < maxDecimals ? $scope.addzero(decimalValue + '0', maxDecimals) : decimalValue;
};
}
};
答案 0 :(得分:0)
将require: 'testDirective'
添加到指令定义,即:
.directive('testDirective', function () {
return {
require: 'testDirective',
link: function ($scope, element, attribute, controller) {
...
},
controller: function ($scope, $element, $attrs) {
...
}
};
});