是一种将链接函数中的元素传递给指令内的控制器函数而不是另一个指令作为元素的方法吗?
我的意思是我有一个指令:
angular.module('myApp').directive('parentDir', function() {
return {
restrict: 'E',
link: function (scope, element, attributes) {
element = //some HTML code
},
controller: function ($scope) {
this.elem = function () {
$scope.elem = element;
}
}
}
});
然后我有另一个指令,我希望得到$scope.elem
。
angular.module('myApp').directive('childDir', function() {
return {
restrict: 'E',
link: function (scop, elmn, attr){
// HOW TO GET THE $scope.elem here as elmn ?
elmn = $scope.elem ?
}
}
});
是否可以将element
传递给$scope.elem
而不是另一个指令?
编辑:感谢大家的帮助,我还通过factory
under this link
答案 0 :(得分:4)
我认为您正在寻找child指令从父指令获取元素的方法。您可以使用指令到指令通信的常用技术来执行此操作,其中child指令可以访问父指令的控制器:
家长目录:
angular.module('myApp').directive('parentDir', function() {
return {
restrict: 'E',
link: function (scope, element, attributes) {
element = //some HTML code
},
controller: function ($scope, $element) {
this.elem = function () {
return $element;
}
}
}
});
儿童指令:
angular.module('myApp').directive('childDir', function() {
return {
restrict: 'E',
require: '^parentDir',
link: function (scop, elmn, attr, parentCtrl){
var parentElmn = parentCtrl.elem();
}
}
});
答案 1 :(得分:1)
这取决于你想要实现的目标。如果要从子控制器访问父控制器,那么最好的选择是使用require并在子控制器的链接功能中注入父控制器。
如果您只需要访问范围,您还可以在子指令中将范围设置为false。但是这种方法可能会导致一些混乱,因为代码变得更加复杂。
下面是一个如何从child指令(我的首选方法)
访问父指令的示例
angular.module('app', [])
.directive('parentDir', function() {
return {
restrict: 'E',
template: '<div style="background: yellow">This is the parent dir and value is <strong>{{ val }}</strong><div ng-transclude></div></div>',
transclude: true,
replace: true,
controller: function($scope, $element) {
$scope.val = true;
this.element = $element;
this.updateVal = function(newVal) {
$scope.val = newVal
}
}
}
})
.directive('childDir', function() {
return {
restrict: 'E',
require: '^parentDir',
replace: true,
template: '<div class="append" style="background: red; margin: 15px"><h5>This is the child dir</h5><button ng-click="change()">change parent scope</button></div>',
link: function(scope, element, attr, parentCtrl) {
//if you want access to the parent element
var parentElem = parentCtrl.element;
//if you want to execute a function in the parent directive
scope.change = function() {
//note that because of protoypical inheritance, scope.val can be accessed in the child directive
parentCtrl.updateVal(!scope.val)
}
}
}
});
<html ng-app='app'>
<head>
<script src='https://code.angularjs.org/1.3.15/angular.js'></script>
<script src='script.js'></script>
</head>
<body>
<parent-dir>
<child-dir>
</child-dir>
</parent-dir>
</body>
</html>
希望这会有所帮助。