2017-08-28 8 views
1

なぜ私のディレクティブに更新を渡すことができないのかに関する私の抱擁を失いました。AngularJS =?バインドが更新されていません

次のコードで達成しようとしているのは、ボタンを押してフォーカスをオンにできるようにすることです。しかし、問題は、drWrapで変更されるたびに変更する必要があるときにディレクティブがロードされたときにのみ、drInputの "フォーカス"バインディングが設定されることです。どのように私はこれを回避するのですか?

今、皆さん、私はあなたにプレゼントします:コード!

<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/

+2

私はあなたのjsfiddleの前にいますが、どういう意味ですか?「しかし、この問題は、ディレクティブがロードされたときにバインディングが設定されているだけです。どうして、どうすればこの問題を回避できますか?」 – quirimmo

+0

私は精緻化しました。ありがとうございました ;-) –

答えて

3

あなたがscope: { focus: '=?bind' }を書くとき、これは属性名がbindなくfocusなければならないことを意味し、そのdrWrapのテンプレートは次のようになります。

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

drInput指令にngBlurイベントハンドラを追加したいとinput

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

入力を偽に変更するその焦点を失った。

ここはworking fiddleです。

関連する問題