为什么我的指令会创建一个新范围?

时间:2013-10-06 08:52:05

标签: angularjs angularjs-directive angularjs-scope

下面是我编写的一个简单指令,用于在脚本元素中插入本地存储的HTML块。

以下是它的使用方法:

<body>
   <div my-partial="partial1"></div>
</body>

<script id="partial1" type="text/html">
   <div>
      <button ng-click="OK()">OK</button>
   </div>
</script>

代码确实做了我想要的但我看到当部分模板使用指令替换元素时,它上面有ng-scope类。这让我觉得创建了一个新的范围,但这不是我的意图。我只是希望插入HTML并成为现有范围的一部分。

为什么会这样?

这是指令:

   app.directive("myPartial", ["$compile", function ($compile)
    {
        var def =
        {
            restrict: 'A',
            scope:false,
            compile: function (element, attributes, transclude)
            {
                var tmplID = attributes.myPartial,        //Get templateID
                    markup = $("#" + tmplID).html(),      //Load partial template markup <text node>
                    partial = $("<div>").html(markup);    //Stick markup text into a <div> so it'll become real DOM elements

                partial = partial.contents();             //Don't need that outer <div> anymore

                if (!partial.length) { throw "myPartial: " + tmplID + " not found"; }

                //Replace this element w/ the partial template markup
                element.replaceWith(partial);


                //PostLink
                //---------------------------------------------------------------------
                return function postLink(scope, element, attributes, modelController)
                {
                    //Compile the partial and link it w/ the current scope
                    $compile(partial)(scope);
                }
            }
        };

        return def;
    }]);

感谢您提供任何帮助或建议的代码改进。

2 个答案:

答案 0 :(得分:0)

回答您的第二个问题: 您无法访问编译功能内的范围。出于详细原因,请阅读Angular.js Repository Wiki中的“Understanding Directives”。 只需将值定期绑定到您的作用域,并使用链接函数根据需要修改作用域。

答案 1 :(得分:0)

我认为问题与后期链接功能有关。在这种情况下,我不相信我应该有一个。

这似乎有效:

 {
        restrict: 'A',  //Attribute
        scope: false,   //Don't create a new scope

        compile: function(element, attributes, transclude)
        {
            //Get partial template
            var partial = $("#" + attributes.asmPartial);

            //Add the partial to the element
            element.html(partial.html());

            //Remove the element leaving only the partial
            element.contents().unwrap();
        }
    }