使用NG-模型NG-transclude内的原始值 [英] Use ng-model with a primitive value inside ng-transclude

查看:251
本文介绍了使用NG-模型NG-transclude内的原始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个传统的项目,我想创建一个使用transclude一个新的指令。

In a legacy project, I want to create a new directive that uses transclude.

指令code的修剪下来的版本是:

A trimmed down version of the directive code is:

app.directive('controlWrap', function() {
    return {
        restrict: 'E',
        transclude: true,
        scope: { label: "@" },
        templateUrl: "control-wrap-template.html"
    }
})

和模板是:

<div>
    <label>{{label}}</label>
    <div>
        <ng-transclude></ng-transclude>
    </div>
</div>

此指令用于这样

<control-wrap label="Just a example">
    <input type="text" ng-model="input" />
</control-wrap>
Test: {{input}}

我知道的解决方法的是范围,而不是原始值使用对象(的> NG-模型)。但是,这对我来说是没有选择。这是一个丑陋,不善codeD,遗留code,在这些属性直接依赖的范围。

I know that the workaround is to use a object in the scope instead of primitive value (ng-model inside ng-transclude). But that is no option for me. It is a ugly, poorly coded, legacy code that relies in those attributes directly on the scope.

有没有什么我可以在指令做,以使该HTML的作品没有变化?

Is there a something I can do in the directive to make that html works without change?

推荐答案

您可以手动transclude(而不是使用 NG-transclude ),并应用这是什么范围(,你的情况, $范围父),你需要的内容transcluded:

You can manually transclude (instead of using ng-transclude) and apply whatever scope (which is, in your case, scope.$parent) you need to the transcluded content:

transclude: true,
scope: { label: "@" },
template: '<div>\
             <label>{{label}}</label>\
             <placeholder></placeholder>\
           </div>',
link: function(scope, element, attrs, ctrls, transclude){
   transclude(scope.$parent, function(clone){
      element.find("placeholder").replaceWith(clone);
   });
}

演示

Demo

这篇关于使用NG-模型NG-transclude内的原始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆