AngularJS:动态编译指令模板时适当的范围绑定

Joh*_*Doe 5 angularjs angularjs-directive angularjs-scope

特定

  • 指令D1应用于元素E.
  • 指令D1传递一个包含指令D2的模板
  • 指令D2订阅了ngModel更新
  • 指令D1使用指令D2编译模板
  • 指令D1和D2被认为是彼此独立的
  • 指令D1和D2具有隔离的范围
  • (指令D1可能与DOM分离,但保留在内存中)

目的

  • make指令D2对应用了D1的元素E的范围变化作出反应

的index.html

<div ng-app="myApp" ng-controller="MainCtrl">
<label>
    <u>model: </u>
    <input type="text" ng-model="someValue" outer="tmpl.html"/>
    <hr/>
</label>

<script type="text/ng-template" id="tmpl.html">
    <inner test="123"></inner>
</script>

<script src="angular.js"></script>
Run Code Online (Sandbox Code Playgroud)


app.js

(function (ng) {

var app = ng.module('myApp', []);

app.controller('MainCtrl', [
    '$scope',
    function ($scope) {
        $scope.someValue = 'Hello, World!';
    }
])
// directive D2
.directive('inner', function () {
    return {
        restrict: 'AE',
        replace: true,
        template: '<p>{{model || "N/A"}}</p>',
        scope: { model: '=ngModel' },
        link: function (scope, element, attrs) {
            scope.$watch('model', function (newValue, oldValue) {
                if (!ng.isDefined(oldValue) && !ng.isDefined(newValue)) {
                  return;
                }
                // do stuff...
            });
        }
    };
})
// directive D1
.directive('outer', [
    '$templateCache',
    '$compile',
    function ($templateCache, $compile) {
        return {
            restrict: 'AE',
            scope: {},
            link: function (scope, element, attrs) {
                var template = $templateCache.get(attrs.outer);
                var compiled = $compile(template)(scope);
                element.parent().append(compiled);
            }
      };
    }
]);

})(angular);
Run Code Online (Sandbox Code Playgroud)

小提琴

这里有一个过于简化的版本:http://jsfiddle.net/Nscp8/12/

D1是一个弹出窗口小部件,可以配置为插入HTML作为其内容. D2是一个QR码小部件,可以观察模型并更新更新.

问题

ngModel绑定未正确完成,我没有从中获取更新.我在这做错了什么?

a b*_*ver 3

scope: { model: \'=ngModel\' },

\n\n

这会将属性绑定到元素model属性中定义的属性,因为您以元素的形式使用该指令。您的元素没有这样的属性。ng-modelinnerinner

\n\n

但即使有,第二个问题是 的父作用域inner是 的作用域outer,它也是一个隔离作用域。someValue是在controller\xc2\xb4s范围中定义的,因此无论您选择哪种绑定类型,inner都没有机会直接与 建立绑定。someValue

\n\n

解决方案取决于您的具体需求。请参阅此小提琴以获取一种可能的解决方案。

\n