如何从控制器外部的指令将变量传递给控制器​​?

时间:2015-08-20 10:27:38

标签: angularjs angularjs-scope

我需要获取一些在ng-view div中设置的属性(在主控制器范围之外)。使用自定义指令传递属性值是我猜的解决方案..所以我有:

<body ng-app="myapp">
    <!--Load ng-view and add attrs-->
    <div ng-view 
         my-directive 
         first-attr="attrOne" 
         second-attr="attrSecond">
    </div>
</body>

指令:

.directive('myDirective', myDirective);

function myDirective() {
    var directive = {
        restrict: 'AE',
        link:link,
        scope: {
            firstVal: '=firstAttr',
            secondVal: '=secondAttr'
        }
    };
    return directive;
}

应用设置和控制器:

angular
    .module('myapp', [
        'ui.router'
    ])
    .config(function ($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.otherwise('/myApp');
        $stateProvider
            .state('myApp', {
                url: '/myApp',
                templateUrl: 'main.html',
                controller: 'mainCtrl'
            });

    });

.controller(mainCtrl, mainCtrl);

function mainCtrl ($scope) {

}

是否可以在加载页面时在主控制器中获取这些属性值?

提前致谢!

1 个答案:

答案 0 :(得分:0)

假设'mainController'和指令之间存在父子关系。

您可以使用事件发射器

指令:

.directive('myDirective', myDirective);

function myDirective() {
    var directive = {
        restrict: 'AE',
        link:link,
        controller:controller
        scope: {
            firstVal: '=firstAttr',
            secondVal: '=secondAttr'
        }
    }
    return directive;

    function controller($scope){
        //SOME LOGIC
        $scope.firstVal = "firstVal LOGIC"
        $scope.secondVal = "secondVal LOGIC"

        //EMIT AFTER LOGIC DONE
        var data = { firstVal: $scope.firstVal, secondVal: $scope.secondVal};
        $scope.$emit('YOUR_CONTROLLER_EVENT', data);
    }
}

控制器:

.controller(mainCtrl, mainCtrl);

function mainCtrl ($scope) {
    $scope.$on('YOUR_CONTROLLER_EVENT', function(event, data){
        var firstVal = data.firstVal;
        var secondVal = data.secondVal;
    });
}