Angularjs “访问父对象”;孤立的;子指令的作用域

Angularjs “访问父对象”;孤立的;子指令的作用域,angularjs,scope,Angularjs,Scope,我有一个嵌套指令。我试图访问父指令的范围(它是孤立的),但似乎无法使其工作。在尝试将其注销到控制台时,会出现未定义的错误 这里有一个我正在努力工作的例子 app.directive("myParentControl", function() { return { restrict: "A", scope: {}, controller: function($scope) { $scope.propertyOne =

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

这里有一个我正在努力工作的例子

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";
        }
    }
})

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

在控制器中设置属性:

controller: function($scope) {
    this.propertyOne = "PropertyOne";
},
如果需要从
myParentControl
的模板访问它,请使用
controllerAs
属性将控制器置于作用域中:

app.directive("myParentControl", function() {
    return {
        ...
        controllerAs: "ctrl",
        ...
    };
});
从模板中,以以下方式访问它:

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

您可以使用子指令中的
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";
        }
      }
    })

谢谢你的回答。如果我这样做,我似乎不再能够从myParentControl的链接功能中的控制台日志访问控制器-我该如何保持这种连接?此外,我还以为一个必需的指令的想法是通过$scope传递的?很抱歉,混淆了-只是想让我的头脑清醒一下。为了从链接功能访问此指令的控制器,
需要
此指令并正常进行。-不,需要指令不会带来范围,只会带来控制器。需要声明所需内容的控制器…好的…。很好,它可以工作。感谢您的帮助!