AngularJS使用指令填充输入字段,但未在$scope中捕获
当我从指令中填充输入字段时,它会显示在DOM上,但$scope没有捕获值。如何修复它以使$scope捕获新信息 如何从我的小提琴中重现这种行为:AngularJS使用指令填充输入字段,但未在$scope中捕获,angularjs,angularjs-directive,angularjs-scope,Angularjs,Angularjs Directive,Angularjs Scope,当我从指令中填充输入字段时,它会显示在DOM上,但$scope没有捕获值。如何修复它以使$scope捕获新信息 如何从我的小提琴中重现这种行为: Click Fill with Directive Click Log --> $scope.input val is undefined Fill input with 'asdf' Click Log --> $scope.input val is 'asdf' Fill input with 'abcd' Click Fill w
Click Fill with Directive
Click Log
--> $scope.input val is undefined
Fill input with 'asdf'
Click Log
--> $scope.input val is 'asdf'
Fill input with 'abcd'
Click Fill with Directive
--> DOM shows 'quick brown fox'
Click Log
--> $scope.input val is 'abcd'
我的代码在这里:
JS:
HTML:
充满指令
日志结果
您发布的代码有问题:
在链接函数中,您的作用域应该是scope
而不是$scope
。
如果希望在控制器和指令之间进行双向绑定,则需要通过隔离作用域传入变量。但是,对于隔离作用域,fillFormDirective()
方法如果在没有fill input
指令的元素上声明,则不会被调用
试试这个:
app.directive('fillInput', function(){
return {
scope:{
fillInput:'='
}
link: function(scope, elem){
elem.val(scope.fillInput);
elem.bind("click", function(e){
console.log(elem);
elem.val('quick brown fox');
});
}
};
});
以及您的HTML:
编辑我已更新plunk以不使用隔离作用域。此SO线程的解决方案: 工作许可证: 基本上,引用“Stewie” ngModel侦听“输入”事件,因此要“修复”代码,您需要在设置值后触发该事件:
elem.bind("click", function(e){
console.log(elem);
newElem.val('quick brown fox');
newElem.triggerHandler('input'); <-----This line of code fixed the problem
});
elem.bind(“点击”,函数(e){
控制台日志(elem);
纽兰·瓦尔(“敏捷的棕色狐狸”);
newElem.triggerHandler('input');在你的链接函数中,你的作用域应该是scope
而不是$scope
。这将帮助你fillFormDirective
可以访问与fillInput
@zeroflagL相同作用域的每个指令。谢谢你的更正。我已经更新了我的答案。实际上我不知道。我还假设OP需要控制器和指令之间的双向绑定,但是,是的,在隔离作用域fillFormDirective
的上下文中,其他元素将无法访问。谢谢。@MohammadSepahV,它仍然不起作用。我在这里更新了您的plunkr:。注意,使用指令更新输入不会触发ngModel,所以请继续sole日志未定义。如果您手动在字段中键入内容,它会正确记录。@RyanWKan InsidefillFormDirective
您应该记录scope.text
,而不是scope.input
@RyanWKan,很抱歉,我现在有点困惑,用一句话告诉我您到底想做什么。
app.directive('fillInput', function(){
return {
scope:{
fillInput:'='
}
link: function(scope, elem){
elem.val(scope.fillInput);
elem.bind("click", function(e){
console.log(elem);
elem.val('quick brown fox');
});
}
};
});
elem.bind("click", function(e){
console.log(elem);
newElem.val('quick brown fox');
newElem.triggerHandler('input'); <-----This line of code fixed the problem
});