javascript - angularjs中嵌套的directive之间如何进行scope通讯?
本文介绍了javascript - angularjs中嵌套的directive之间如何进行scope通讯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
html代码
<div ng-controller="parentController">
<button-bar>
<button class="primary" ng-click="onPrimary1Click()">{{primary1Label}}</button>
<button class="primary">Primary2</button>
</button-bar>
</div>
js代码
var testapp = angular.module('testapp', []);
testapp.controller('parentController', ['$scope', '$window', function($scope, $window) {
console.log('parentController scope id = ', $scope.$id);
$scope.primary1Label = 'Prime1';
$scope.test=222;
$scope.onPrimary1Click = function() {
$window.alert('Primary1 clicked');
};
}]);
testapp.directive('primary', function() {
return {
restrict: 'C',
scope: false,
link: function(scope, element, attrs) {
alert(scope.test);
element.addClass('btn btn-primary');
}
}
});
testapp.directive('buttonBar', function() {
return {
restrict: 'EA',
template: '<div class="span4 well clearfix"><div class="pull-right" ng-transclude></div></div>',
replace: true,
transclude: true,
scope: false,
link: function(scope, element, attrs) {
scope.test=111;
//alert(scope.primary1Label);
}
};
});
scope: false下buttonBar和primary都能得到controller中的test=222,但是如何能在buttonBar中修改test,并使primary获取到修改后的值呢?
解决方案
如果你非要这么做的话,应该用引用类型:
var testapp = angular.module('testapp', []);
testapp.controller('parentController', ['$scope', '$window', function($scope, $window) {
console.log('parentController scope id = ', $scope.$id);
$scope.primary1Label = 'Prime1';
$scope.test= { test2: 222 };
$scope.onPrimary1Click = function() {
$window.alert('Primary1 clicked');
};
}]);
testapp.directive('primary', function() {
return {
restrict: 'C',
scope: false,
link: function(scope, element, attrs) {
alert(scope.test.test2);
element.addClass('btn btn-primary');
}
}
});
testapp.directive('buttonBar', function() {
return {
restrict: 'EA',
template: '<div class="span4 well clearfix"><div class="pull-right" ng-transclude></div></div>',
replace: true,
transclude: true,
scope: false,
link: function(scope, element, attrs) {
scope.test.test2 = 111;
//alert(scope.primary1Label);
}
};
});
这篇关于javascript - angularjs中嵌套的directive之间如何进行scope通讯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文