我不确定这是否是实现此目的的方法,但我的目标如下:
- 我有一个父指令
- 在父指令的 block 内,我有一个子指令,它将从用户那里获取一些输入
- 子指令将在父指令的范围内设置一个值
- 我可以从那里拿走它
当然,问题在于父指令和子指令是同级指令。所以我不知道该怎么做。注意 - 我不想在
中设置数据fiddle :http://jsfiddle.net/rrosen326/CZWS4/
html:
<div ng-controller="parentController">
<parent-dir dir-data="display this data">
<child-dir></child-dir>
</parent-dir>
</div>
Javascript
var testapp = angular.module('testapp', []);
testapp.controller('parentController', ['$scope', '$window', function ($scope, $window) {
console.log('parentController scope id = ', $scope.$id);
$scope.ctrl_data = "irrelevant ctrl data";
}]);
testapp.directive('parentDir', function factory() {
return {
restrict: 'ECA',
scope: {
ctrl_data: '@'
},
template: '<div><b>parentDir scope.dirData:</b> {{dirData}} <div class="offset1" ng-transclude></div> </div>',
replace: false,
transclude: true,
link: function (scope, element, attrs) {
scope.dirData = attrs.dirData;
console.log("parent_dir scope: ", scope.$id);
}
};
});
testapp.directive('childDir', function factory() {
return {
restrict: 'ECA',
template: '<h4>Begin child directive</h4><input type="text" ng-model="dirData" /></br><div><b>childDir scope.dirData:</b> {{dirData}}</div>',
replace: false,
transclude: false,
link: function (scope, element, attrs) {
console.log("child_dir scope: ", scope.$id);
scope.dirData = "No, THIS data!"; // default text
}
};
});
最佳答案
如果您想要这种通信,则需要在子指令中使用require
。这将需要父 Controller
,因此您需要一个 Controller
,其中包含您希望子指令使用的功能。
例如:
app.directive('parent', function() {
return {
restrict: 'E',
transclude: true,
template: '<div>{{message}}<span ng-transclude></span></div>',
controller: function($scope) {
$scope.message = "Original parent message"
this.setMessage = function(message) {
$scope.message = message;
}
}
}
});
Controller 在 $scope
中有一条消息,并且您有一个方法可以更改它。
为什么一个在 $scope
中,另一个在 this
中?您无法访问子指令中的 $scope
,因此您需要在函数中使用 this
,以便您的子指令能够调用它。
app.directive('child', function($timeout) {
return {
restrict: 'E',
require: '^parent',
link: function(scope, elem, attrs, parentCtrl) {
$timeout(function() {
parentCtrl.setMessage('I am the child!')
}, 3000)
}
}
})
如您所见,链接接收带有parentCtrl 的第四个参数(或者如果有多个参数,则接收一个数组)。这里我们只等待 3 秒,直到调用我们在父 Controller 中定义的方法来更改其消息。
关于Angularjs:使用子指令设置父指令范围值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18501127/