javascript - AngularJS 自定义生成的指令动态属性绑定(bind)

标签 javascript jquery html angularjs

在我的场景中,我有一个指令,它将另一个指令标记作为范围参数。然后第一个指令需要生成新指令并将其附加到其中。它还需要将动态双向绑定(bind)属性添加到新生成的指令中。

我能够生成新的指令标签,但是当我尝试添加指令属性时,它会将其附加为字符串(值或简单字符串)。 因此,当我尝试在新指令中将属性作为范围变量访问时,它会给我“未定义”。

HTML:

<div ng-controller="MainCtrl">
===
<directive1 tag="obj.tag" request-id="requestId"></directive1>
</div>

指令:

app.directive('directive1', function($compile) {
return {
    restrict: 'E',
    scope:{
        tag:"=",
        requestId:"="
    },
    link: function(scope, element, attrs) {
        var el;
        scope.$watch('tag', function (tpl) {
            console.log("8888",tpl);
            el = $compile(tpl)(scope);
            el.attr('request-id', scope.requestId);
            el = $compile(el)(scope);
            element.append(el);
        });
        // attrs.$set('ngHide', false);
        // attrs.$set('hide', null);
        // $compile(element)(scope);
    }
};
})
app.directive('test', function($compile) {

    return {
        restrict: 'E',
        scope:{
          requestId:"="
        },
        controllerAs: 'requestCtrl',
        bindToController: true, //required in 1.3+ with controllerAs

        controller:function(){
          var requestCtrl=this;
          console.log("----->>>> ",requestCtrl.requestId)
        },
        link: function(scope, element, attrs) {
        }
    };
});

Controller :

app.controller('MainCtrl', function($scope) {
    $scope.obj={};
    $scope.obj.tag="<test></test>";
    $scope.requestId="123";
});

这是 plunker

最佳答案

您的 plunker 使用的是 angular 1.0.2,它不支持 bindToController 但是,更改为 1.3 将使它像您的问题中所述的字符串绑定(bind)一样工作。

要将 requestId 用作双向绑定(bind),您需要将字符串 requestId 传递到 attr。

el.attr('request-id', 'requestId');

Working plunker

关于javascript - AngularJS 自定义生成的指令动态属性绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45668822/

相关文章:

css - 绝对位置背景100%页面高度

javascript - 当我设置这些时,为什么我的表单不进行验证检查?

javascript - 返回一个围绕 promise 的 promise

html - jQuery 中缺少带空格的 HTML 属性值

javascript - 使用 Jquery 更改 Input[type=range] 拇指样式 - 不工作

javascript - 链接到同一页面上的 anchor 减去一些像素

javascript - 如何在react组件中使用一个类的方法?

javascript - 以 Angular 限制同时异步 $http get 请求

html - 为什么 "Inline-block"在此 CSS 中不能正常工作?

php - php 中的电子邮件 div 内容