如何使用angularJS正确绑定指令和控制器之间的范围

前端之家收集整理的这篇文章主要介绍了如何使用angularJS正确绑定指令和控制器之间的范围前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图用anugularJS生成一个n级的无序列表,并且能够成功地这样做。但现在,我在指令和控制器之间存在范围问题。我需要通过在指令模板中通过ng-click调用函数中更改父对象的scope属性

http://jsfiddle.net/ahonaker/ADukg/2046/ – 这是JS

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

//myApp.directive('myDirective',function() {});
//myApp.factory('myService',function() {});

function MyCtrl($scope) {
    $scope.itemselected = "None";
    $scope.organizations = {
        "_id": "SEC Power Generation","Entity": "OPUNITS","EntityIDAttribute": "OPUNIT_SEQ_ID","EntityID": 2,"descendants": ["Eastern Conf Business Unit","Western Conf Business Unit","Atlanta","Sewanee"],children: [{
            "_id": "Eastern Conf Business Unit","Entity": "","EntityIDAttribute": "","EntityID": null,"parent": "SEC Power Generation","descendants": ["Lexington","Columbia","Knoxville","Nashville"],children: [{
                "_id": "Lexington","EntityID": 10,"parent": "Eastern Conf Business Unit"
            },{
                "_id": "Columbia","EntityID": 12,{
                "_id": "Knoxville","EntityID": 14,{
                "_id": "Nashville","EntityID": 4,"parent": "Eastern Conf Business Unit"
            }]
        }]
    };

    $scope.itemSelect = function (ID) {
        $scope.itemselected = ID;
    }
}

app.directive('navtree',function () {
    return {
        template: '<ul><navtree-node ng-repeat="item in items" item="item" itemselected="itemselected"></navtree-node></ul>',restrict: 'E',replace: true,scope: {
            items: '='
        }
    };
});

app.directive('navtreeNode',function ($compile) {
    return {
        restrict: 'E',template: '<li><a ng-click="itemSelect(item._id)">{{item._id}} - {{itemselected}}</a></li>',scope: {
            item: "=",itemselected: '='
        },controller: 'MyCtrl',link: function (scope,elm,attrs) {
            if ((angular.isDefined(scope.item.children)) && (scope.item.children.length > 0)) {
                var children = $compile('<navtree items="item.children"></navtree>')(scope);
                elm.append(children);
            }
        }
    };
});

这里是HTML

<div ng-controller="MyCtrl">
    Selected: {{itemselected}}

    <navtree items="organizations.children"></navtree>
</div>

注意列表是从模型生成的。并且ng-click调用函数来设置父范围属性(itemselected),但更改仅在本地发生。当我点击一个项目时,预期的行为是“已选择:无”应该更改为“所选:xxx”,其中xxx是被点击的项目。

我没有适当地绑定父范围和指令之间的属性吗?如何将属性更改传递给父范围?

希望这很清楚。

提前感谢任何帮助。

请看这个工作小提琴, http://jsfiddle.net/eeuSv/

我做的是要求navtree-node指令中的父控制器,并调用该控制器中定义的成员函数
成员函数为setSelected。请注意,它的this.setSelected而不是$ scope.setSelected。
然后定义navtree-node范围方法itemSelect。当您点击锚标签时,它会在navtree-node范围上调用itemSelect方法。这个inturn将调用控制器成员方法setSelected传递所选的id。

scope.itemSelect = function(id){myGreatParentControler.setSelected(ID)}

猜你在找的Angularjs相关文章