2016-09-11 1 views
0

아래에 코드 스 니펫이 있습니다.angularjs의 컨트롤러 내부에서 일반적인 자바 스크립트 함수를 정의하는 방법

sample.js 여기

(function() { 
    /*global angular */ 
    'use strict'; 

    angular.module('myapp', ['spinner']) 
     .controller('myCtrl', ['$scope', '$window', function ($scope, $window) { 

    $scope.methodname = function() { 
      if(something){ 
       /* Doing some operations */ 
      } 
    }; 
    /* Here I need to define the callme javascript function */ 

    function callme(response){ 
     /* If I call like this, I'm getting error in console. */ 
    } 

    }]); /* Controller ends here */ 

    /* Creating a new anonymous function to perform some operations */ 
    (function() { 
    'use strict'; 


    /* Edited */ 
    code.util.myHTTP(url, function (response) { 

      // Adding response to session storage 
      callme(response); 

      }, function() { 
       // Removing from session storage 
     }); 

     })(); 
    }()); 

, 내가 할 수없는 각 컨트롤러 내부에 자바 스크립트 함수 callme를 호출 할 수 있습니다. 같은 콘솔에서 오류가 발생했습니다

Uncaught ReferenceError: callme is not defined 

이 방법이 있습니까?

나는 callme 함수 내에서 $ window와 같은 컨트롤러 매개 변수를 사용해야하므로 컨트롤러 내부에 callme 함수를 정의합니다. 내 JS 파일에 함수를 실행 한

이미

.run(function($rootScope, $log, $window) { 
}); 

내 요구 사항은 전화 익명 함수처럼 아래 부하에 나는 응답을 처리하는 하나의 방법을 호출 할 필요가 일부 API 응답이있을 것이다 좋아한다. 이러한 컨트롤러 매개 변수 때문에 컨트롤러 내부에 내 메서드를 정의하려고했습니다. 이것을 달성하기위한 다른 방법이 있습니까?

+0

로직이 꺼져 있습니다. 컨트롤러 외부에서'callme '을 정의하거나 (컨트롤러에서 호출 할 수 있음), 또는 여러분이 만든 다른 범위 안에 정의하십시오. –

+0

그러면 컨트롤러 외부에서 callme를 호출하면 $ scope를 어떻게 사용할 수 있습니까? –

+0

다른 변수를 전달할 때'callme'에'$ scope'를 인자로 넘길 수 있습니다. (예 : 컨트롤러에서 :'callme ($ scope, response);'). –

답변

0

들여 쓰기가 모두 자리를 잡고 있으며이 코드를 이해하기 어렵게 만듭니다. 다음은 올바른 형식의 코드는 ...입니다

(function() { 
    /*global angular */ 
    'use strict'; 

    angular.module('myapp', ['spinner']) 
    .controller('myCtrl', ['$scope', '$window', function ($scope, $window) { 
     $scope.methodname = function() { 
     if (something) { 
      /* Doing some operations */ 
     } 
     }; 
     /* Here I need to define the callme javascript function */ 

     function callme (response) { 
     /* If I call like this, I'm getting error in console. */ 

     } 
    }]); /* Controller ends here */ 

    /* Creating a new anonymous function to perform some operations */ 
    (function() { 
    'use strict'; 

    /* Edited */ 
    code.util.myHTTP(url, function (response) { 

     // Adding response to session storage 
     callme(response); 
    }, function() { 
     // Removing from session storage 
    }); 
    })(); 
}()); 

function 선언 그들의 범위의 상단에를 게양하지만, 그 범위 밖에 존재하지 않기 때문에이 작동하지 않는 이유는.

(function() { 
    function MyController($scope) { 
    $scope.methodname = function() {} 

    function callme(response) { 
    } 
    } 

    (function() { 
    callme() 
    }()) 
}()) 

callme는하지만 MyController의 상단에 게양된다 : 우리는 일부 cruft에를 제거하는 경우,이 코드가 간소화 것입니다. 그 심볼은 해당 범위 밖에서 존재하지 않으므로 중첩 된 범위에서 callme()을 수행 할 수 없습니다.

당신이하는 일은 반 패턴과 같습니다. 이를 달성 할 수 있다고해도 core.util.myHTTP은 Angular 다이제스트주기 내에서 실행되지 않으므로 컨트롤러 내부에서 $scope.$apply으로 전화해야합니다. 이는 일반적으로 나쁜 것으로 간주됩니다. 대체로 $http 대신 사용 하시겠습니까? 당신이 정말이 (당신이하지 않는)이 작업을 수행하려면

그럼에도 불구하고, 당신과 같이 함수를 정의 할 수 있습니다 :

(function() { 
    function callme(response) { } 

    function MyController($scope) {} 

    (function() { 
    ... 
    callme() 
    }()) 
}()) 

은 또는 당신에 따라 지침 (또는 구성 요소를 사용할 수있는 사용자 각도 버전) 대신 이것을 처리해야합니다. 어떻게해야하는지입니다.

function SpinnerCtrl($http) { 
    this.$http = $http 
} 
SpinnerCtrl.$inject = ['$http'] 
SpinnerCtrl.onInit = function onInit() { 
    var that = this 
    return this.$http.get(url) 
    .then(function (response) { 
     // Store it in session storage, do whatever. 
     // Presumably there's some data you want to make accessible to other parts of the app, so I assign it to the controller here 
     that.response = response 
    }) 
} 

angular.module('myapp', ['spinner']) 
    .component('spinner', { 
    controller: SpinnerCtrl, 
    template: '<h1>{{ $ctrl.response }}</h1>' 
    }) 

// or 

function SpinnerCtrl($scope, $http) { 
    return $http.get(url).then(function (response) { 
    $scope.response = response 
    }) 
} 

angular.module('myapp', ['spinner']) 
    .directive('spinner', function() { 
    return { 
     controller: SpinnerCtrl, 
     template: '<h1>{{ response }}</h1>' 
    } 
    }) 

정말로 $ http 호출을 서비스로 옮기고 거기에 세션 저장소를 처리해야합니다. 세션 저장소는 구현 세부 사항이며이를 사용하는 구성 요소/지시문은 신경 쓸 필요가 없습니다. 나는 간결함을 위해서 그렇게하지 않았다.

+0

click 이벤트가있을 때 methodname을 호출 할 수 있습니다. 이 callme 함수는 click 이벤트로부터 응답을 얻은 후에 호출합니다. 이 경우이 코드가 작동합니까? –

+0

어, 그렇 겠지? 그러나이 경우'callme' 기능이 컨트롤러 외부에 있어야 할 이유가 무엇입니까? 왜 그것은 동거 될 수 없는가? 이런 식으로 코드를 레이아웃해야하는 이유를 알기 위해 고심하고 있습니다. Angular 싸이클 밖에서 $ http 호출을하는 것에 대한 당신의 주장은 당신에게 많은 골칫거리입니다. 당신은 그것을 정당화 할 수 있습니까? –

+0

실행 중에이 익명 함수를 사용할 수 있습니까? callme 함수를 호출 할 수 있습니까? –

관련 문제