문제

나는 점진적으로 각도 지침을 매달리고 지금까지 컨트롤러 간의 중개자로서의 서비스를 만드는 것에 의지했다.

Directives (및 링크 기능)의 맥락에서 컨트롤러 액세스가 연결 기능의 변수에 액세스 할 수 있습니까?(서비스 또는 글로벌 변수없이).

module.exports = function() {
    return {
      restrict: 'A',
      templateUrl: 'partials/collection',
      link: function(scope, element, attrs) {
        var name = attrs.collectionName;
        // from here
      },
      controller: function($scope, socket) {
        $scope.models = [];
        // to here
        socket.on('ready', function() {
          socket.emit(name + '/get');
        });

      }
    }  
  };
.

Collection-name 속성의 값을 내 컨트롤러 내에서 사용할 수 있으므로 적절한 소켓 호출을 할 수 있습니다.어떤 아이디어가 있습니까?

도움이 되었습니까?

해결책

동일한 범위를 공유하므로 작동해야합니다.

module.exports = function() {
    return {
      restrict: 'A',
      templateUrl: 'partials/collection',
      link: function(scope, element, attrs) {
        scope.name = attrs.collectionName;
        // from here
      },
      controller: function($scope, socket) {
        $scope.models = [];
        // to here
        socket.on('ready', function() {
          socket.emit($scope.name + '/get');
        });

      }
    }  
  };
.

다른 팁

컨트롤러에 메서드를 추가하고 링크 기능에서 호출 할 수 있습니다.

controller: function($scope, socket) {
   this.setSocket = function(name){
       {...}
   }
}
.

링크 :

link: function(scope, element, attrs, controller){
    var name = attrs.collectionName; 
    controller.setSocket(name);
}
.

There are a couple of ways of doing what you want

  • Just put everything in the link function. You can set functions and variables on the scope just like you might put in a controller.

  • Just put everything in the controller, in terms of setting scope variables or functions. It is injected with $attrs, which contains the normalised attribute values, so you have access to the attributes if you need them.

As far as I know, in most cases it doesn't make a difference where you assign variables or functions on the scope. The main difference between the two is that if you want to give your directive a public API, so other directives can communicate to it via require, then you must use this.something in the controller.

There maybe a better way to do it, but I've managed to get around the problem by changing my controller functions dependencies to include an $element argument. Then just used jqLite to get the value of the attribute in question.

controller: function($scope, $element, socket) {
   var name = $element.attr('collection-name');
}

It's not fantastically elegant, but it works.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top