AngularJS通过$ compile的动态内容范围未附加到控制器范围

时间:2013-04-09 20:18:43

标签: javascript angularjs angularjs-directive angularjs-scope angularjs-controller

当我通过具有指令的字符串生成新元素时(这就是我需要编译的原因)并且该指令通过“=”生成与控制器范围中的变量的关联,我的控制器中的变量不是与指令中的那个相关联。

我创建了一个jsfiddle来显示“门”ng模型值应该与所有指令模型值相关联的示例。

看到这个小提琴:http://jsfiddle.net/aVJqU/2/

我注意到的另一件事是,从html中存在的元素运行的指令通过变量(控制器和指令)显示正确的关联。

html(有绑定<door>的指令):

<body ng-app="animateApp">
    <div ng-controller="tst">
        <h2> Controller with its model </h2>
        <input ng-model="doorval" type="text"> </input>
        {{doorval}}
        <h2> Directive render directly from the html </h2>
        <door doorvalue="doorval"></door> <key></key>
        <h2> Directives that are compiled </h2>
        <list-actions actions="actions"></list-actions>
    </div>
</body>

这是指令:

animateAppModule.directive('door', function () {
    return {
        restrict: "E",
        scope: {
            doorvalue:"="
        },
        template: '<span>Open the door <input type="text" ng-model="doorvalue"> </input> {{doorvalue}}</span>',
        replace: true
    }
})

这是控制器:

var animateAppModule = angular.module('animateApp', [])

animateAppModule.controller('tst', function ($scope, tmplService) {
    $scope.doorval = "open"
    $scope.actions = tmplService;

})
animateAppModule.service('tmplService', function () {
    return [{
        form_layout: '<door doorvalue="doorval"></door> <key></key>'
    }, {
        form_layout: '<door doorvalue="doorval"></door> with this <key></key>'
    }]
})

最后,这是编译具有不绑定指令的字符串的指令:

animateAppModule.directive('listActions', function ($compile) {
    return {
        restrict: "E",
        replace: true,
        template: '<ul></ul>',
        scope: {
            actions: '='
        },
        link: function (scope, iElement, iAttrs) {
            scope.$watch('actions', function (neww, old,scope) {
                var _actions = scope.actions;
                for (var i = 0; i < _actions.length; i++) {
                   //iElement.append('<li>'+ _actions[i].form_layout + '</li>');
                    //$compile(iElement.contents())(scope)
                    iElement.append($compile('<li>' + _actions[i].form_layout + '</li>')(scope))
                }
            })
        }
    }
})

如何将所有“门”ng模型值绑定在一起? 编译指令绑定到哪里?

2 个答案:

答案 0 :(得分:5)

您必须通过所有指令传递doorval引用,而不必跳过任何指令。问题是listActions指令在其范围内无法访问doorval。 看看这个:http://jsfiddle.net/aVJqU/5/

答案 1 :(得分:0)

@Danypype基本上是正确的,因为范围隔离会导致问题发生,如documentation中所述。

另一种解决方案是通过从指令定义中删除范围块来简单地消除范围隔离。

相关问题