Angularjs 访问控制器中的指令值
我意识到已经有类似的问题了,但我找不到解决问题的办法 我有以下指令,为光标离开的输入框(模糊)提取一个键和值:Angularjs 访问控制器中的指令值,angularjs,Angularjs,我意识到已经有类似的问题了,但我找不到解决问题的办法 我有以下指令,为光标离开的输入框(模糊)提取一个键和值: 这可能会在多个控制器之间使用,因此我的问题是如何从任何控制器访问键和值值?如果我理解正确,您正在尝试访问ngModel的值,这样做的最“有角度的方式”是在您的指令中要求ngModelController这样做 return { restrict: 'A', require: 'ngModel', link: function(scope, element, at
这可能会在多个控制器之间使用,因此我的问题是如何从任何控制器访问
键
和值
值?如果我理解正确,您正在尝试访问ngModel的值,这样做的最“有角度的方式”是在您的指令中要求ngModelController这样做
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
element.bind('blur', function() {
var model = ngModelCtrl.$modelValue;
});
}
};
您可以找到有关ngModelController的更多信息是的,您可以将控制器范围变量传递给指令,并使用此变量访问指令中的值 示例
<input type="text" update-one-field my-scope="myVariable" />
现在,像这样更新你的指令
.directive('updateOneField', function() {
return {
restrict: 'A',
scope: {
myScope: '='
},
link: function(scope, element, attr) {
element.bind('blur', function() {
var key = attr.ngModel.split('.');
key = key[key.length - 1];
// Get the input value
var value = element[0].value;
// Assign key and value to controller variable
scope.myScope = {};
scope.myScope.Key = key;
scope.myScope.Value = value;
});
}
};
});
现在,您可以从控制器访问键和值
,就像
// Code inside your controller
$scope.myVariable.Key; // Get key from the directive
$scope.myVariable.Value; // Get value from the directive
希望这会有所帮助。如果您对此有任何疑问,请随时添加评论。您在指令声明中有一个输入错误:
.directive('updateOneField', function() {
return {
restrict: 'A',
// her -------------------------------> scope: [],
scope : {},
link: function(scope, element, attr) {
element.bind('blur', function() {
var key = attr.ngModel.split('.');
key = key[key.length - 1];
// Get the input value
var value = element[0].value;
});
}
};
});
多亏了你的问题,我才找到了这个博客,它真的解释了指令中的范围,也非常清楚地解释了指令。看一看,谢谢你的投票:)
// Code inside your controller
$scope.myVariable.Key; // Get key from the directive
$scope.myVariable.Value; // Get value from the directive
.directive('updateOneField', function() {
return {
restrict: 'A',
// her -------------------------------> scope: [],
scope : {},
link: function(scope, element, attr) {
element.bind('blur', function() {
var key = attr.ngModel.split('.');
key = key[key.length - 1];
// Get the input value
var value = element[0].value;
});
}
};
});