用AngularJS绑定指令

Directive binding with AngularJS

本文关键字:指令 绑定 AngularJS      更新时间:2023-09-26

我在AngularJS中创建了一个自定义指令。在link函数中,我将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;
});

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

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

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

你可以在这里详细说明你真正想要达到的目标。

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

解决方案: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元素/树)绑定到作用域