父控制器中无法访问Angular指令范围

时间:2017-11-07 15:14:06

标签: javascript angularjs angularjs-scope angular-directive

我正致力于角度应用 关于将direcive方法调用到父控制器的问题,我陷入了困境。 问题是我在配置文件控制器上使用登录指令。 我想从配置文件控制器的范围调用login direcive的方法。

Firstproblem是我无法通过在控制器中使用$ scope.login.openLogin(false)来调用login指令的方法 因为此处未定义$ scope.login。 但是在同一个控制器中,可以在回调事件中访问$ scope.login.openLogin(false),如ajax调用的成功或错误方法。但我不知道有些时间也是未定义的,有些时间工作正常。这是我的主要问题,无法找出为什么有些时候$ scope.login可以访问,有些时候没有。

第一个问题是我无法在配置文件控制器中获取$ scope.vm或$ scope.login。我无法像$ sope.vm.getData()那样调用方法,而是必须像this.getData()一样调用它。为什么this.getData()是可访问的但是$ scope.vm.getData()不可访问它会给出null

以下是登录指令的代码

LoginDirective.cs

//Login diretive 
angular.module('EmailApp')
    .directive('login', function LoginDrctv() {
        'use strict';
        return {
            restrict: 'EA',
            replace: true,
            scope: false,
            templateUrl: "js/directives/template/login.tmpl.html",
            controllerAs: 'login',
           //bindToController: true,
            controller: function (LoginFactory, $scope, $rootScope, $location) {

                //THis method is to be call from parent controller (Profile Controller)
                this.openLogin = function (IsmakeCall) {
                    debugger;
                    this.loginOperation = "Login";
                    this.makeCall = IsmakeCall;   //true or false
                  //  $rootScope.islogin = true;
                    $scope.vm.mainPage = 'login';
                }
            },
            link: function (scope, element, attrs, ctrl) {
                /* 
                  by convention we do not $ prefix arguments to the link function
                  this is to be explicit that they have a fixed order
                */
            }
        }
    });

Profile Controller(Profile.Js)

angular.module('EmailApp')
    .controller('ProfileCtrl', ['$rootScope', '$routeParams', 'DetailFactory', '$scope', '$location',
        function ProfileCtrl($rootScope, $routeParams, DetailFactory, $scope, $location) {

            'use strict';
            this.loading = true;
            this.mainPage = 'detail';
            this.back = function () {
                $location.path('home');
            }
           // $scope.login.openLogin(false)  this method is not accessible 
           //here but in call back function is works like below
            this.getData = function () {
                debugger;
                this.loading = true;
                DetailFactory.getDetailProfile().then(function (resp) {
                    $scope.vm.loading = false;
                    $scope.vm.userDetails = resp.data;
                    $scope.vm.userId = resp.data.appUser.UserID
                }, function (err) {
                    $scope.vm.loading = false;
                    if (err.status == 401) {
                        //Call method of login directive .It get called some 
                        //times but sometime $scope.login gives undefined
                        $scope.login.openLogin(false);
                    }
                });
            }
            this.getData();
        }]);

profile.html

angular.module('EmailApp', [
    'ngRoute',
    'ngSanitize',
    'angularFileUpload'
]).config(function ($routeProvider) {

    'use strict';
    $routeProvider
        .when('/profile', {
            templateUrl: 'view/profile.html?v=' + Math.random(),
            controller: 'ProfileCtrl',
            controllerAs: 'vm'
        })
        .when('/home', {
            templateUrl: 'view/PrivacyPolicy.html?v=' + Math.random(),
            controller: 'PrivacyCtrl',
            controllerAs: 'vm'
        })
        .otherwise({
            redirectTo: '/home'
        });
    }).run(function ($rootScope, $location) {
});

1 个答案:

答案 0 :(得分:0)

通常,父控制器不会对子控制器或指令进行函数调用。而是将值传递到指令DOM并在指令上添加$watch以了解该值何时发生更改。

以下是执行$watch

的代码
<!DOCTYPE html>
<html ng-app="myApp">
  <head>
    <meta charset="utf-8">
    <title>Angular Callback</title>
    <style>
    .login {
      border: 1px solid black;
    }

    .login:not(.login--opened) .login-inner {
      display: none;
    }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script>
    var myApp = angular.module("myApp", []);

    myApp.controller('appController', function($scope) {
      $scope.loginIsOpen = false;

      $scope.openLogin = function() {
        $scope.loginIsOpen = true;
      }

    });


    myApp.controller('loginController', loginController);
    loginController.$inject = ['$scope'];
    function loginController($scope) {
      $scope.closeMe = function() {
        $scope.isOpen = false;
      }

      $scope.$watch('isOpen', function(newVal) {
        if (newVal === true) {
          console.log('The Login was opened');
        }
      });
    }

    myApp.directive('login', loginDirective );
    function loginDirective() {
      return {
        'restrict': 'E',
        'template': '<div class="login" ng-class="{\'login--opened\':isOpen}">Login Directive<div class="login-inner"><p>I am open</p><button ng-click="closeMe()">Close</button></div></div>',
        'controller': 'loginController',
        'scope': {
          isOpen: '='
        }
      };
    }
    </script>
  </head>
  <body ng-controller="appController">
    <button ng-click="openLogin()">Open Login</button>
    <hr/>
    <login is-open="loginIsOpen"></login>
  </body>
</html>