programing

동일한 디렉티브의 링크 함수 내에서 디렉티브 컨트롤러의 기능 사용

jooyons 2023. 3. 31. 22:02
반응형

동일한 디렉티브의 링크 함수 내에서 디렉티브 컨트롤러의 기능 사용

디렉티브 컨트롤러가 어떻게 동작하는지에 대한 근본적인 오해는 있을 수 있습니다.다른 디렉티브 및 컨트롤러에 노출되는 API로 사용되는 것으로 알고 있습니다.컨트롤러와 링크 기능을 사내에서 통신하려고 합니다.

예를 들어 컨트롤러 함수를 통해 변수를 설정하고 링크 함수에서 사용할 수 있습니다.

var app = angular.module('test-app', []);

app.directive('coolDirective', function () {
    return {
        controller: function () {
            this.sayHi = function($scope, $element, $attrs) {
                $scope.myVar = "yo"
            }
        },
        link: function(scope, el, attrs) {
            console.log(scope.myVar);
        }   
    }
});

링크 기능 내에서 myVar 또는 sayHi에 액세스하려면 어떻게 해야 합니까?아니면 제가 요점을 완전히 놓쳤나요?

양쪽 컨트롤러의 $scope (컨트롤러가 아닌 컨트롤러에서 정의)sayHi기능) 및 링크scope똑같아요.컨트롤러 내의 설정은 링크 또는 그 반대로 사용할 수 있습니다.

당신의 문제점은sayHi발화되지 않는 기능이기 때문에myVar설정되지 않았습니다.

부터sayHi는 스코프에 포함되지 않습니다.컨트롤러에 대한 참조가 필요합니다.그러려면 다음과 같은4번째 파라미터를 추가합니다.

link: function(scope, element, attr, ctrl) {}

그럼 넌 할 수 있어ctrl.sayHi()(하지만 다시 말하지만, 그 가사들은sayHi컨트롤러 기능에 속합니다.)

다른 컨트롤러가 필요하지만 그 디렉티브를 사용하려면 그 컨트롤러도 필요합니다.그래서 만약에 이게coolDirective컨트롤러에 액세스 할 필요가 있다notCoolAtAll다음 작업을 수행할 수 있습니다.

require: ['coolDirective', 'notCoolAtAll']

그것으로 족하다.link함수는 컨트롤러의 배열을 네 번째 파라미터로 수신하고 이 경우 첫 번째 요소는coolDirectivectrl과 두 번째 것은notCoolAtAll하나.

다음은 예를 제시하겠습니다.http://plnkr.co/edit/JXahWE43H3biouygmnOX?p=preview

위의 코드를 다시 쓰면 다음과 같습니다.

var app = angular.module('test-app', []);

app.directive('coolDirective', function() {
    return {
        controller: function($scope) {
            // bind myVar property to scope
            $scope.myVar = 'yo';
            // bind sayHi method to scope
            $scope.sayHi = sayHi;
            // abstracting out the sayHi function
            function sayHi() {
                console.log($scope.myVar);
            }
        },
        link: function(scope, el, attrs) {
            // execute the sayHi function from link
            scope.sayHi(); // "yo" in console
        }
    };
});

행운을 빌어요.

언급URL : https://stackoverflow.com/questions/20864294/using-functions-from-directive-controller-within-link-function-of-same-directive

반응형