2014-07-14 35 views
0

我在指令中嵌套了select2輸入,我想將所選值綁定到外部作用域。我怎樣才能做到這一點。 plunker exampleui-select2內部指令綁定到外部作用域

指令代碼:

app.directive('optionChoices', function() { 
    return { 
    restrict: 'EA', 
    scope: { 
     type: '=', 
     selections: '=' 
    }, 
    template: '<input ng-if="type === 1" ui-select2="textChoices" ' + 
       'ng-model="selections" style="width:200px" />' + 
       '<input ng-if="type === 2" ui-select2="colorChoices" ' + 
       'ng-model="selections" style="width:200px" />' + 
       '{{\'inner:\' + selections}}', 
    link: function (scope, element, attrs) { 
     function Query(query) { 
     var data={ 
      results:[] 
     }; 
     if (query.term.length > 0) { 
      data.results.push({id:query.term,text:query.term}); 
     } 
     query.callback(data); 
     } 
     scope.textChoices = { 
     query: Query, 
     tags: [], 
     initSelection: function() {} 
     }; 
     scope.colorChoises = angular.extend({}, scope.textChoices, { 
     formatSelection: function(state) { 
      if (!state.id) return state.text; 
      return "<div style='background-color:yellow;'>&nbsp;</div>" + state.text; 
     } 
     }); 
    } 
    }; 
}); 

回答

0

我發現這個問題,這並不難。 創建獨立作用域時,不能只綁定到父作用域,如果doens angular會創建一個單獨的變量實例。 只需要綁定到$父或與母對象:

scope: { 
     option: '=' 
    } 

,並在模板:

template: '<input ng-if="option.type === 1" ui-select2="textChoices" ' + 
       'ng-model="option.selections" style="width:200px" />' + 
       '<input ng-if="option.type === 2" ui-select2="colorChoices" ' + 
       'ng-model="option.selections" style="width:200px" />' + 
       '{{\'inner:\' + selections}}', 

NJOY!