0

我将 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;
        }
      });
    }
  };
});
4

1 回答 1

0

我找到了问题所在,这并不难。创建隔离作用域时,不能只绑定到父作用域,如果这样做,角度会创建一个单独的变量实例。只需要绑定到 $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}}',

开心!

于 2014-07-15T15:46:21.327 回答