簡體   English   中英

Angular指令范圍在父控制器中不可訪問

[英]Angular directive scope not accessible in parent controller

我正在做一個角度應用程序,我陷入了一個關於將直接方法調用到父控制器中的問題。 問題是我在配置文件控制器上使用登錄指令。 我想從配置文件控制器的范圍調用login direcive的方法。

Firstproblem是我無法在控制器中使用$ scope.login.openLogin(false)來調用登錄指令的方法,因為$ scope.login在此處未定義。 但是在同一個控制器中,在回調事件(如ajax調用的成功或錯誤方法)中可以訪問$ scope.login.openLogin(false)。 但是我不知道有沒有時間未定義,有一些時間工作正常。這是我的主要問題,無法找出為什么有一段時間$ scope.login可以訪問而有一段時間沒有訪問。

第一個問題是我無法在配置文件控制器中獲取$ scope.vm或$ scope.login。我無法調用諸如$ sope.vm.getData()之類的方法,而是必須像this.getData()這樣來調用它。 .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.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) {
});

通常,父控制器不會對子控制器或指令進行函數調用。 而是將一個值傳遞到指令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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM