访问父控制器的当前实例重复

时间:2015-07-16 14:47:20

标签: javascript angularjs nested

我有:

<div ng-controller="fooControlle as fc">
    <div ng-repeat"fooObj in fc.fooCollection">
        <div ng-controller="barController as bc" ng-init="bc.init()">
            bc output here
        </div>
    </div>
</div>

我需要从bc.init()访问fooObj。

我试过了:

ng-init="bc.init(fooObj)"

但fooObj未知。

通过我的init函数使用$ parent,我会看到我的收藏,但不会知道哪一个是我当前的项目。

有什么想法? 提前谢谢。

3 个答案:

答案 0 :(得分:1)

我建议您将$index$parent.fooObj一起传递,以便跟踪您在哪个元素

<div ng-controller="fooControlle as fc">
    <div ng-repeat"fooObj in fc.fooCollection">
        <div ng-controller="barController as bc" ng-init="bc.init($parent.fooObj, $parent.$index)">
            bc output here
        </div>
    </div>
</div>

为了让它更好,你的fooObj应该有一个独特的值,可以区分它,就像你应该有像fooObj = {id: 1, .....}

这样的东西

答案 1 :(得分:0)

个人而言,easiet将为barController部分创建一个指令,并将fooObj作为参数传递给指令

app.directive("foo", [function(){
    return {
         restrict: "E",
         controller: "barController",
         templateUrl: "",
         scope: {
            bar: "="
         }
    };
}]);

然后你的html可能是

<div ng-controller="fooControlle as fc">
    <div ng-repeat"fooObj in fc.fooCollection">
        <foo bar="fooObj"></foo>
    </div>
</div>

答案 2 :(得分:0)

谢谢你们的回答。 Pankaj,你告诉我的方式:)

最后它很简单,有两个选项:

ng-init="bc.init($parent.fooObj)"

var init = function(){
    var foo = $parent.fooObj
}

第二种方式显然更清晰,因为当你可以从函数中以相同的方式访问它时,通过参数发送值没有附加价值。

  

这里的关键是我误解了 $ parent 在这里的内容。当它是ng-repeat 当前迭代上下文时,我认为是父控制器上下文

感谢您的协助。

相关问题