2017-08-28 65 views
1

为什么我无法将更新传递给我的指令,我已经失去了方向。AngularJS =?bind not updating

我试图用下面的一段代码来完成的是,可以通过按下一个按钮来设置焦点。然而,问题在于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() 
        } 
        }) 
      } 
     } 
    }]) 

和提琴! https://jsfiddle.net/L56rdqLp/168/

+2

我在你的jsfiddle之前,但是......你是什么意思,“问题是,只有当指令加载时才会设置绑定,怎么回事,我该如何解决这个问题? – quirimmo

+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