【问题标题】:Access parent controller from ng-included HTML从包含 ng 的 HTML 访问父控制器
【发布时间】:2015-07-27 12:47:51
【问题描述】:

我想从包含 ng 的 html 访问控制器中的函数,该 html 包含带有 html 模板的指令。

含义,给定带有控制器的父 html 模板:

<div ng-controller="profileCtrl">
    <div ng-include src="profileContent"></div>
</div>

profileCtrl:

$scope.profileContent = '/html/views/myview.html';
$scope.test = 'This should show';

myview.html:

<my-directive></my-directive>

我的指令:

angular
    .module('myModule')
    .directive('myDirective', [function () {
        return {
            restrict: 'E',
            templateUrl: '/html/directives/myDirectiveTemplate.html',
            ...

myDirectiveTemplate.html:

{{test}} //should output "This should show"

如何从子 myDirective 访问 $scope.test?


myDirectiveTemplate.html:

<form ng-submit="$parent.updateProfile()">

profileCtrl:

    $scope.updateProfile = function() {
        console.log('updating profile'); //not called

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    这样试试

    {{$parent.test}}
    

    【讨论】:

    • 好的,太好了!但是,我实际上想从该父控制器中的函数上的子指令调用ng-submit 上的函数。 $parent.test 输出很好,但如果我调用updateProfile,它就不会运行。见上文
    • 你能为此提供一个 plunkr 吗?
    • Anik,发现了我的问题。我将我的指令表格包装在一个引导手风琴中。这个手风琴捕获了其中的范围,这意味着我需要执行 $parent.$parent.ctrlFunction() 来访问控制器中的函数。
    猜你喜欢
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    相关资源
    最近更新 更多