与AngularJS绑定的指令

时间:2013-04-25 07:17:31

标签: javascript angularjs angularjs-directive

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

2 个答案:

答案 0 :(得分: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;
});

您可能想要详细说明您真正希望在此实现的目标。

答案 1 :(得分: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元素/树)绑定到范围