如何从另一个控制器angularjs调用控制器功能

时间:2014-10-15 22:37:22

标签: angularjs angularjs-scope angular-services

请看这段代码。我的按钮必须从控制器CtrlTwo调用函数checkResults()。 怎么做?



var myApp = angular.module('myApp', []);

function CtrlOne($scope){
    $scope.greet = 'Hi!  ';
}

function CtrlTwo($scope){
    $scope.$emit('checkResults', function(){
        alert('Function is called!');
    }
                );
}

<body ng-app="myApp">
    <div ng-controller="CtrlOne">
        {{greet}}
        <input type="submit" class="btn btn-primary pull-right" value="Check results" ng-href='#here' ng-click='checkResults()'/>
    </div>
    
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</body>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

在此,希望此示例可以帮助您:

使用Javascript:

var myApp = angular.module('myApp', []);

myApp.controller('CtrlOne', function($scope){
    $scope.greet = "hi!"
    var nTimes = 0;
    $scope.$on('myEvent', function(){
        $scope.greet = "Hi! The event has been called " + (++nTimes) + " times";
    });
});

myApp.controller('CtrlTwo', function($scope){
    $scope.emitCustomEvent = function(){ $scope.$emit('myEvent'); };
});

查看:

<div ng-app="myApp">
    <div ng-controller="CtrlOne">
        {{greet}}
        <div ng-controller="CtrlTwo">
            <input type="button" value="Check results" ng-click="emitCustomEvent()" >
        </div>
    </div>
</div>

Working Example