【问题标题】:How to call controller function from other controller angularjs如何从另一个控制器angularjs调用控制器函数
【发布时间】:2014-12-11 03:57:18
【问题描述】:

请看这段代码。我的按钮必须从控制器 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>

【问题讨论】:

    标签: angularjs angularjs-scope angular-services


    【解决方案1】:

    在这里,希望这个例子对你有所帮助:

    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

    【讨论】:

    • 谢谢约瑟夫。这个答案对我有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    相关资源
    最近更新 更多