ui-select2 inside指令绑定到外部作用域

时间:2014-07-14 13:51:27

标签: angularjs ui-select2

我在指令中嵌套select2输入,我想将选定的值绑定到外部作用域。我怎样才能做到这一点。 plunker example

指令代码:

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;
        }
      });
    }
  };
});

1 个答案:

答案 0 :(得分:0)

我发现了问题,并没有那么难。 在创建隔离范围时,您不能只绑定到父范围,如果doens angular将创建一个单独的变量实例。 只需要绑定到$ parent,或者绑定到父对象:

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!