1

我在 AngularJS 中创建了一个自定义指令。在链接函数中,我将 ng-model 和 ng-options 属性添加到内部模板,但不幸的是,绑定不起作用。但是当我将内部模板原样放入我的 html 文件时,一切正常。

application.directive("customSelect", function () {
var directive = {
    restrict: 'E',
    template: '<select name="ArrDeplocation" class="arrdepSelect"></select>',
    link: function (scope, elem, attr) {
        console.log('scope: ', scope);
        console.log('element: ', elem);
        console.log('attribute: ', attr);

        $(elem.children()[0]).attr('ng-model', 'model.selectedCity');
        $(elem.children()[0]).attr('ng-options', 'city for city in model.cities');

        $(elem.children()[0]).selectmenu();

    }
};
return directive;
});
4

2 回答 2

3

我不明白为什么需要在链接函数中设置属性。您可以简单地放入您的模板中。

http://plnkr.co/edit/9u6nkLYKHxBBiJ60mpbF?p=preview

app.directive("customSelect", function () {
  var directive = {
    restrict: 'E',
    template: '<select name="ArrDeplocation" class="arrdepSelect"'
     + 'ng-model="model.selectedCity" ng-options="city for city in model.cities">    </select>',
    link: function (scope, elem, attr) {
      // run jquery mobile methods here...
    }
  };
  return directive;
});

您可能想在这里详细说明您真正想要实现的目标。

于 2013-04-25T08:13:54.077 回答
0

如果你想在链接函数中修改你的模板,那么你必须重新编译它。

解决方案:http ://plnkr.co/edit/bpiqXdQe91RJBaJXTPXO?p=preview

app.directive("customSelect", function ($compile) {
  return {
    restrict: 'E',
    template: '<select name="ArrDeplocation" class="arrdepSelect"></select>',
    link: function (scope, elem, attr) {
      elem.find('select').attr({
        'ng-model':   'model.selectedCity',
        'ng-options': 'city for city in model.cities'
      });
      var tpl = elem.html();
      elem.html($compile(tpl)(scope));
      elem.find('select').selectmenu();
    }
  };
});

$compile("html string")模板编译为:

用于将模板(DOM 元素/树)绑定到范围的链接函数

于 2013-11-20T18:36:27.710 回答