如何在没有控制器的情况下添加$ scope。$ on

时间:2016-04-09 05:52:51

标签: javascript angularjs angularjs-directive event-listener

我在Angular应用中使用了一个触发$rootScope.$broadcast('signinBegin')的插件。我希望preloader显示ng-if,但我无法使用此控制器添加$scope.$on('signinBegin',function(){...})。如何在HTML视图中启动事件时显示没有控制器的预加载器?

<div ng-if="preloader">
    <img src="../assets/img/preloader/material.gif" alt="preloader">
</div>
<div id="sign-form" class="panel panel-default">
    <div class="panel-body">
        <div class="row">
            <div class="col-md-12">         
                <!--  ng-submit should be signin() -->
                <form ng-submit="signin()" role="form" autocomplete="off" class="form-horizontal">
                    <fieldset>                                      
                        <div  class="input-group">
                            <span class="input-group-addon"><i class="fa fa-user"></i></span>
                            <input ng-model="user.email" type="text" class="form-control" id="email" placeholder="Email" required>
                        </div>
                        <div class="spacing"></div>
                        <div  class="input-group">
                            <span class="input-group-addon"><i class="fa fa-key"></i></span>
                            <input ng-model="user.password" type="password" class="form-control" id="password" placeholder="Password">
                        </div>
                        <div class="spacing"></div>
                        <button type="submit" class="btn btn-success btn-sm  pull-right">Sign In</button>
                    </fieldset>
                </form>
                <a ui-sref="forget-password" class="grey">Forget Password?</a>
            </div>

        </div>

    </div>
</div>

和这个app.config

app.config(function($stateProvider,$urlRouterProvider,$locationProvider,$authProvider) {
    $authProvider.signinState = 'login';
    $authProvider.signinRoute = '/login';

我使用ng-AA插件。

由于

1 个答案:

答案 0 :(得分:1)

您可以使用指令。例如:

myApp.directive('signinBeginFoo', function() {
   return {
       scope: true,
       link: function($scope) {
           $scope.$on('signinBegin', function() {
               $scope.preloader = true;
           });
       }
   }
});

现在,修改您的DOM:

<signin-begin-foo>
    <div ng-if="preloader">
        <img src="../assets/img/preloader/material.gif" alt="preloader">
    </div>
</signin-begin-foo>