gpt4 book ai didi

javascript - AngularJS =?绑定(bind)不更新

转载 作者:行者123 更新时间:2023-11-30 11:31:56 27 4
gpt4 key购买 nike

我无法理解为什么我无法传递指令更新。

我试图用以下代码完成的是能够通过按下按钮来设置焦点。然而,问题是只有当指令加载时,drInput 上的“焦点”绑定(bind)才会设置,而当它在 drWrap 中更改时它应该更改。怎么会以及如何解决这个问题?

现在,女士们先生们,我向你们介绍:代码!

<div ng-app="myApp">
<dr-wrap></dr-wrap>
</div>


var myApp = angular.module('myApp', []);

myApp.directive('drWrap', function($timeout) {
return {
scope: {
focus: '=?bind'
},
restrict: 'E',
replace: 'true',
template: '<div><button ng-click="openSearch()">focus</button><dr-input focus="focusSearch" /></div>',
link: function(scope, elem, attr){
scope.openSearch = function(){
$timeout(function(){
scope.focusSearch = true
alert('scope.focusSearch 2 = ' + scope.focusSearch)
}, 1000)
}
}
};
})
.directive('drInput', function() {
return {
scope: {
focus: '=?bind'
},
restrict: 'E',
replace: 'true',
template: '<input type="test" focus-me="{{ focus }}" />',
link: function(scope, elem, attr){
scope.$watch('focus', function(value){
if(value != undefined){
scope.focus = value
alert('scope.focus = ' + scope.focus)
}
})
}
};
})
.directive('focusMe', ['$timeout', function ($timeout) {
return {
link: function (scope, element, attrs) {
attrs.$observe('focusMe', function(value){
if ((value === true) || (value == 'true')) {
$timeout(function () {
element[0].focus()
scroll(element[0])
})
} else {
element[0].blur()
}
})
}
}
}])

还有 fiddle ! https://jsfiddle.net/L56rdqLp/168/

最佳答案

当您编写 scope: { focus: '=?bind' } 时,这意味着属性名称应该是 bind 而不是 focus,所以 drWrap 的模板应该是这样的:

template: '<div><button ng-click="openSearch()">focus</button><dr-input bind="focusSearch" /></div>'

添加ngBlur drInput 指令 input 的事件处理程序,例如:

template: '<input type="test" focus-me="{{ focus }}" ng-blur="focus = false"/>',

当输入失去焦点时,将模型更改为 false。

这里是 working fiddle .

关于javascript - AngularJS =?绑定(bind)不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45924324/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com