Ros*_*s R 12 angularjs angularjs-directive angularjs-scope
我不确定这是怎么做的,但我的目标如下:
当然问题是父指令和子指令都是兄弟姐妹.所以我不知道该怎么做.注意 - 我不想在中设置数据
小提琴:http://jsfiddle.net/rrosen326/CZWS4/
HTML:
<div ng-controller="parentController">
<parent-dir dir-data="display this data">
<child-dir></child-dir>
</parent-dir>
</div>
Run Code Online (Sandbox Code Playgroud)
使用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
}
};
});
Run Code Online (Sandbox Code Playgroud)
Jes*_*uez 27
如果您想要这种通信,则需要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;
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
控制器中有一条消息$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)
}
}
})
Run Code Online (Sandbox Code Playgroud)
如您所见,链接接收带有parentCtrl的第四个参数(或者如果有多个,则为数组).这里我们等待3秒,直到我们调用我们在父控制器中定义的方法来更改其消息.
在此处观看:http : //plnkr.co/edit/72PjQSOlckGyUQnH7zOA?p=preview
首先,观看此视频.它解释了一切.
基本上,你需要require: '^parentDir'
然后它将被传递到你的链接功能:
link: function (scope, element, attrs, ParentCtrl) {
ParentCtrl.$scope.something = '';
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20617 次 |
最近记录: |