Angularjs指令模板转换

时间:2013-11-20 09:58:08

标签: javascript angularjs

我有一个像这样的元素:

<input test class="foo bar" ng-model="foo" name="foo"/>

当我有“test”属性时,我试图把它变成类似下面的例子:

<div class="something">
    <input type="text" class="foo bar" ng-model="foo" name="foo"/>
    <span>test</span>
</div>

但是我遇到了翻译问题,而不是转移到输入的属性,它们被转移到div,所以我最终会得到类似的东西:

<div class="something foo bar" type="text" ng-model="foo" name="foo">
    <input/>
    <span>test</span>
</div>

这是指令:

.directive('test', [function () {
     return {
        transclude:true,
        replace:true,
        template:'<div class="something">\
            <input ng-transclude>\
            <span>hi</span>\
        </div>',
        link: function (scope, element, attrs, ngModel) {
            // do stuff
        }
    }
}])

3 个答案:

答案 0 :(得分:0)

您将无法以这种方式转换:

<input test class="foo bar" ng-model="foo" name="foo"/><!-- NO -->

我相信你最好的机会(使用元素级指令)是:

<test>
    <input class="foo bar" ng-model="foo" name="foo"/>
</test>

在这种情况下,指令的template将是:

template:
    '<div class="something">\
        <ng-transclude />\
        <span>hi</span>\
    </div>',

答案 1 :(得分:0)

我想你可以尝试这个指令:

<强> JS

var app = angular.module('app',[]);
function myCtrl($scope){

}
app.directive("test",function(){
  return {
    template: '<div class="something"><input type="text" class="foo bar" ng-model="foo" name="foo"/><div ng-transclude></div></div>',
    transclude: true,
    replace: true
  };
});

<强> HTML

<div test ng-controller="myCtrl">
  <span>333</span>
</div>

输出可以解决这个问题:

<div class="something ng-scope" test="" ng-controller="myCtrl">
  <input type="text" class="foo bar ng-pristine ng-valid" ng-model="foo" name="foo">
  <div ng-transclude="">
    <span class="ng-scope">333</span>
  </div>
</div>

jsfiddle demo

希望这对你有所帮助

答案 2 :(得分:0)

显然有可能从AngularJS irc频道获得Foxandxss的链接。

http://plnkr.co/edit/7gOQEODWlJMV9Fe9a9YV?p=preview