javascript - angularjs中嵌套的directive之间如何进行scope通讯?
迷茫
迷茫 2017-04-11 10:56:26
[JavaScript讨论组]

html代码

<p ng-controller="parentController">    
    <button-bar>
        <button class="primary" ng-click="onPrimary1Click()">{{primary1Label}}</button>
        <button class="primary">Primary2</button>
    </button-bar>
</p>

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: '<p class="span4 well clearfix"><p class="pull-right" ng-transclude></p></p>',
        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获取到修改后的值呢?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(1)
伊谢尔伦

如果你非要这么做的话,应该用引用类型:

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: '<p class="span4 well clearfix"><p class="pull-right" ng-transclude></p></p>',
        replace: true,
        transclude: true,
        scope: false,       
        link: function(scope, element, attrs) {
                scope.test.test2 = 111;
                //alert(scope.primary1Label);
        }        
    };
});
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号