【问题标题】:Accessing parent "isolated" scope from child directive从子指令访问父“隔离”范围
【发布时间】:2014-08-09 15:06:23
【问题描述】:

我有一个嵌套指令。我正在尝试访问父指令的范围(它是孤立的),但似乎无法使其工作。尝试将其注销到控制台时出现未定义的错误。

这是我正在努力工作的一个例子。

app.directive("myParentControl", function() {
    return {
        restrict: "A",
        scope: {},

        controller: function($scope) {
            $scope.propertyOne = "PropertyOne"
    },

    link: function(scope, element) {
        console.log(scope.propertyOne);
    }
  }
});

app.directive("myChildControl", function() {
    return {
        require: "^myParentControl",
        link: function(scope, element, attrs, myParentControlCtrl) {
            //Undefined
            console.log(myparentControlCtrl.propertyOne);
            //Not visible in scope inspector
            myParentControlCtrl.newValue = "New Value";
        }
    }
})

【问题讨论】:

    标签: angularjs scope


    【解决方案1】:

    您将变量设置为$scope$scope.propertyOne = "PropertyOne",但尝试从控制器访问它:console.log(myparentControlCtrl.propertyOne)。当然是未定义的。

    在控制器中设置属性:

    controller: function($scope) {
        this.propertyOne = "PropertyOne";
    },
    

    如果您需要从myParentControl 的模板访问它,请使用controllerAs 属性将控制器放入范围内:

    app.directive("myParentControl", function() {
        return {
            ...
            controllerAs: "ctrl",
            ...
        };
    });
    

    从模板访问它:

    <span>{{ ctrl.propertyOne }</span>
    

    【讨论】:

    • 感谢您的回答。但是,如果我这样做,我似乎不再可以从我的控制台登录到 myParentControl 的链接功能访问控制器 - 我将如何维护该连接?另外,我认为 required 指令的想法是通过 $scope?很抱歉造成混乱 - 只是想弄清楚它。
    • 为了从链接函数访问这个指令的控制器,require这个指令并正常进行。 - 不,需要指令不会引入范围,只是控制器。
    • 要求控制器声明需要的东西......好吧.....好吧,它有效。感谢您的帮助!
    【解决方案2】:

    您可以在子指令中使用scope 直接访问父指令的范围。

    myApp.directive("myChildControl", function() {
        return {
            require: "^myParentControl",
            link: function(scope, element, attrs, myParentControl) {
                console.log(scope.propertyOne);
                //Not visible in scope inspector
                myParentControl.newValue = "New Value";
            }
          }
        })
    

    SEE DEMO HERE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-06
      • 1970-01-01
      • 2014-10-12
      • 1970-01-01
      • 1970-01-01
      • 2015-12-08
      • 1970-01-01
      • 2018-11-01
      相关资源
      最近更新 更多