2014-07-14 36 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!