在Angular中更新ng-include from指令

时间:2014-01-25 07:38:25

标签: angularjs

我试图点击通过转发器创建的列表项,并更新ng-inlude正在使用的模板值。在控制器中设置的初始值工作正常(在DOM中显示),但是当我更改指令中的值时,它不会更新DOM(保留为初始包含的DOM)。当我在指令上使用fire bug时,看起来好像范围已经改变,虽然我不确定我是否遗漏了某些东西,或者我是否应该以其他方式这样做。

这是我的部分

 <div ng-controller="menuCtrl" >
    <ul class="sub-menu">
        <li ng-repeat="item in menuItems.left" menu-repeater-directive>
            <span>{{item.name}}</span>
            <a class="reset-menu-btn">&#215;</a>
        </li>
    </ul>

    <div  id="lft-wrapper" class="a-wrapper">
        <div ng-include="template.url" id="lft-scroller" class="a-scroller"></div>
    </div>

</div>

这是我的菜单控制

angular
.module('simApp')
.controller("menuCtrl", function($scope, $element) {

    $scope.menuItems = {

        left: [
            {
                name: "Table of Context",
                url: "static/partials/tree.html"
            },
            {
                name: "Index",
                url: "static/partials/dictionary.html"
            },
            {
                name: "Exercises",
                url: "static/partials/exercises.html"
            },
            {
                name: "Search Results",
                url: "static/partials/results.html"
            }

        ],
        right: [

            {
                name: "About Writer's Help",
                url: "static/partials/about.html"
            },
            {
                name: "Tags & Tools",
                url: "static/partials/tools.html"
            },
            {
                name: "Your Class",
                url: "static/partials/class.html"
            },
            {
                name: "Top Ten",
                url: "static/partials/top10.html"
            }


        ]

    }

    $scope.template = $scope.menuItems.left[0];


});

这是我的指示

angular
    .module('simApp')
    .directive("menuRepeaterDirective", function() {
        return function(scope, element, attrs){

            var self = this;
            this.scope = scope;
            this.element = element;

            var $ele = $(element);
            $ele.find("span").fastClick(function(ev){

                //angular specific
                var index = $(ev.currentTarget).parent().index();
                self.scope.template = self.scope.menuItems.left[index];
                //end angular specific

               ....some other Jquery stuff
            });


        }
    });

1 个答案:

答案 0 :(得分:1)

尝试:

self.scope.$apply(function(){ //Use $apply to let angular aware of the changes.
       var index = $(ev.currentTarget).parent().index();
       self.scope.$parent.template = self.scope.menuItems.left[index]; //accessing self.scope.$parent instead of self.scope
 });

DEMO

解释为什么我们必须访问self.scope。$ parent:

self.scopeng-repeat生成的当前项的范围,而ng-include绑定到menuCtrl的范围。在这种情况下,self.scope.$parent是menuCtrl的范围。