在下面的代码中,我添加了一个控制器来存储可以在子范围内使用的名称,而不使用prelinks.But仍然是名称值未定义。我在哪里出错。
<!DOCTYPE html>
<html ng-app="test">
<head>
<title>AngularJS</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.8/angular.min.js">
</script>
</head>
<body>
<parent></parent>
</body>
<script>
var test1 = angular.module("test", []);
test1.directive("child", function() {
return {
restrict: "E",
template: "<div>{{message1}}</div>",
link: function(scope, ctrl) {
scope.message1 = "i m child of " + ctrl.name;
}
}
});
test1.directive("parent", function() {
return {
restrict: "E",
template: "<div style='color:red'>{{message}}{{name}}" + "<child></child>" + " </div>",
link: function(scope, ctrl) {
scope.name = ctrl.name;
alert(ctrl.name);
scope.message = "hi i am parent ";
},
controller: function() {
this.name = "aditya";
}
}
});
</script>
</html>
答案 0 :(得分:1)
当您使用controller as
语法this
声明父控制器时,可以向指令添加controllerAs
选项并定义控制器的名称:
var test1 = angular.module("test", []);
test1.directive("child", function() {
return {
restrict: "E",
template: "<div>{{message1}}</div>",
link: function(scope) {
scope.message1 = "i m child of " + scope.parentCtrl.name;
}
}
});
test1.directive("parent", function() {
return {
restrict: "E",
template: "<div style='color:red'>{{message}}{{name}}" + "<child></child>" + " </div>",
link: function(scope, element, attrs, ctrl) {
scope.name = ctrl.name;
alert(scope.name);
scope.message = "hi i am parent ";
},
controller: function($scope) {
this.name = "aditya";
},
controllerAs: 'parentCtrl' // Name of the controller
}
});
然后,在您的孩子中,您可以使用其定义的名称scope.parentCtrl.name
来访问父作用域。