2017-08-28 71 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