【问题标题】:Recommended way to extend DOM object in AngularJS without jQuery?在没有 jQuery 的情况下在 AngularJS 中扩展 DOM 对象的推荐方法?
【发布时间】:2015-02-04 18:55:29
【问题描述】:

我正在使用 angularJS(没有 jQuery)、lo-dash.js 和 coffeescript..

以下是我的代码:

      div = document.getElementById('play')
      iframe = document.createElement('iframe');
      iframe.id='iframe_played'
      iframe.width = '420'
      iframe.height = '315'
      iframe.src = './home.html#/video/'+ currentMarker.id
      iframe.frameborder = '0'
      iframe.allowfullscreen = 'true'
      iframe.webkitallowfullscreen = 'true'
      iframe.mozallowfullscreen = 'true'
      div.appendChild(iframe);

看起来有点笨拙..我知道如果我可以使用 jQuery 会非常容易,但不幸的是我没有导入 jQuery,因为 AngularJS 建议不要这样做..

有人对重构它们有什么建议吗? (最好的方法可能是把它们都放在css中。但是src应该是动态的,allowfullscreen似乎不受CSS支持。)谢谢!

【问题讨论】:

标签: javascript angularjs dom coffeescript underscore.js


【解决方案1】:

下面的指令怎么样 (JSFiddle here):-

    todoApp.directive('linkFrame', [function () {
    var directive = {};
        directive.restrict = 'A';
        directive.transclude = 'true';
        directive.scope = { ngModel: '=ngModel'};
    directive.template = '<iframe width="420" height="315" ng-src="{{ngModel}}"></iframe>';

        directive.link = function ($scope, element, attributes) {
        };
    return directive;
}]);

用法很简单:-

<div link-frame ng-model="lnk.link"></div>

我认为指令应该是进行 DOM 操作和嵌入子元素的正确方法。如果您需要更多控制权,可以查看$compile。

如果有帮助请标记为答案!

【讨论】:

    【解决方案2】:
    function newElement(name, params){
    var out = document.createElement(name);
    for(var i in params){
    out.setAttribute(i, params[i])
    }
    return out;
    }
    

    var div = newElement('div', {'class': 'myDiv', id: 'divId'});

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2013-05-08
      • 2017-07-19
      • 1970-01-01
      相关资源
      最近更新 更多