AngularJS =?bind不更新

时间:2017-08-28 17:21:37

标签: javascript angularjs angularjs-directive

关于为什么我不能将更新传递给我的指令,我已经失去了方向。

我想用下面的代码完成的是通过按下按钮来设置焦点。然而问题是只有在指令加载时才设置对drInput的“焦点”绑定,只要它在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/

1 个答案:

答案 0 :(得分:3)

当您撰写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