2014-02-10 7 views
4

특성에 정의 된 메서드 및 속성에 대한 일련의 컨트롤러 액세스 권한을 부여하려고합니다. 지금 내가 함께 온 최고의 구현은 다음과 같습니다AngularJS에서 컨트롤러 특성을 구현하는 방법

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

app.controller('MainCtrl', function($scope, CtrlTrait) { 
    $scope.name = CtrlTrait.presetName; 
    CtrlTrait.setGreeting.call($scope, 'Hello'); 
}); 

app.service('CtrlTrait', function() { 
    this.setGreeting = function(greeting) { this.greeting = greeting; } 
    this.presetName = 'tom'; 
}); 

Plunkr Code

이 괜찮지 만, 내가 직접 만들지 않고도 컨트롤러의 $ 범위를 통해 액세스 할 수 있도록 속성과 방법을 싶습니다 각 컨트롤러의 별칭. 나는 단지 컨트롤러에 서비스를 주입함으로써 템플릿의 속성과 메서드를 사용할 수 있기를 원합니다.

가능하거나 원하는 속성과 메서드가 사전 설정되어있는 $specialCtrlScope과 같은 [wrapper around]/[provider for] $scope을 만들어야합니까?

+0

당신이 원하는 구문의 예를 들어 줄 수 있을까? 'CtrlTrait.setGreeting()'대신'$ scope.setGreeting()'을 호출하기를 원한다는 말입니까? – Hylianpuffball

+0

예! 맞습니다. '$ scope.setGreeting()'을 호출하고 싶습니다. –

+0

여러분은 http://docs.angularjs.org/guide/dev_guide.services.creating_services –

답변

6

이 같은 angular.extend를 사용하여 시도 할 수 있습니다 : 그것은 것입니다 우리는 당신의 서비스 요청 $scope 동일한 기능에 사용할 수 있습니다 angular.extend($scope,CtrlTrait);. 그래서, 당신이처럼 HTML에서 직접 기능을 사용할 수 있습니다 : 여기

<button ng-click="setGreeting('Good bye! ')">Good Bye</button> 

은 당신의 plunker 데모 적응 :

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

app.controller('MainCtrl', function($scope, CtrlTrait) { 
    $scope.name = CtrlTrait.presetName; 
// CtrlTrait.setGreeting.call($scope, 'Hello'); 
    angular.extend($scope,CtrlTrait); 
    $scope.setGreeting('Hello World'); 
}); 

app.service('CtrlTrait', function() { 
    this.setGreeting = function(greeting) { this.greeting = greeting; } 
    this.presetName = 'tom'; 
}); 

http://plnkr.co/edit/BENS78mjFfpc6VCEtgK8?p=preview

+0

이것은 내가하고 싶은 일을 수행하는 가장 올바른 방법입니다. –

+0

좋은 접근 방법입니다. –

1

당신은 당신의 컨트롤러

$scope.setGreeting = CtrlTrait.setGreeting 

에서 아래 시도 할 수 나중에

내가 '이

var app = angular.module('plunker', []); 
    app.controller('MainCtrl', function($scope, CtrlTrait) { 
    $scope.trait = CtrlTrait; 
    $scope.name = $scope.trait.presetName; 
    $scope.trait.setGreeting.call($scope,'Hello'); 
    }); 

    app.service('CtrlTrait', function() { 
    var trait = {}; 
    trait.setGreeting = function(greeting) { this.greeting = greeting; } 
    trait.presetName = 'tom'; 
    return trait; 
    }); 
+0

나는 여전히 함수의 별칭을 지정하지 않아도되지만, 많은 컨트롤러가 특성을 사용할 것이며 새 특성이나 특성을 특성에 정의하면 모든 요소를 ​​업데이트하지 않으려합니다. 나는 그 (것)들을 그것을 다만 원한다. –

+0

@ ogc-nick 위의 스 니펫을 확인하십시오. 희망이 도움이됩니다. :) – Sai

1

을 그래서 시도 COMMENT 후에

$scope.setGreeting.call($scope, 'Hello'); 

편집을 사용할 수 있습니다 전 조립식 면책 조항이 전자 ... 나는 이 아니고이 실제로 그렇게하거나 적어도 그렇게하지 않는 것이 좋습니다. 모듈 방식과 인젝션을 기반으로 구축 된 프레임 워크 내부에서 컨트롤러와 서비스 간의 추가적인 결합을 추가하고 있습니다. 이는 모든 메소드 호출을 저장하기위한 것입니다.

그렇다면 원하는 것을 구현하는 방법이 있습니다. (JSFiddle here)

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

var controllerMaker = function(trait,controllerCode){ 
    return function($scope, $injector){ 

     //'apply' traits to this scope 
     var apply = function(trait){ 
      trait.applyTo($scope); 
     } 
     apply.$inject = [trait]; 
     $injector.invoke(apply); 

     //Finishes the other injections 
     controllerCode.$inject = ['$scope']; 
     controllerCode($scope); 
    }; 
} 

//Here's a sample 'trait' 
app.service('CtrlTrait', function() { 
    this.applyTo = function(obj){ 
     obj.setGreeting = function(greeting) { this.greeting = greeting; } 
     obj.presetName = 'tom'; 
    } 
}); 

//Then, setup your controller like this 
app.controller('GreatController', controllerMaker("CtrlTrait",function($scope){ //Not using injection though! 
    $scope.bleh = $scope.presetName; //will be 'tom' 
})) 

확실히이 가진 약점이있다, 컨트롤러가 주입을 잃고,하지만 당신은 reeeeeeally 원한다면, 당신이 $inject와 aruond 재생 및 요구에 맞는 무언가를 찾을 수있는 확신하는 방법 등이있다.

+0

흠. 그것은 내가 묻는 것을합니다. 그러나 주사를 잃는 것은 너무 높은 가격입니다. 그럼에도 불구하고 +1. –

1

Angular는 객체 인 경우 함수의 반환 값을 주입합니다. 코드에서 그래서 :

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

app.controller('MainCtrl',["$scope","DefaultName","TraitService", function($scope, defaultName, traitService) { 
    $scope.name = defaultName; 
    $scope.OKPressed = function() { 
    traitService.setName($scope.name); 
    }; 

}); 

// You can use .constant() for a constant value; 

app.constant("DefaultName", "tom"); 

app.service('TraitService', function() { 
    var traitService = {}; // The name does't matter 
    traitService.setName = function(name) { 
    // Not this.name = name because (this)is not guaranteed to persist or be the same across injections. 
    // I am only using local storage to illustrate. I usually use $rootScope to store 
    // Global variables. since they are always available on the $scope object without 
    // needing a service. 
    // That might be a better way for you ($rootScope) 
     localStorage.setItem("nameKey", name); 
    } 
    traitService.getName = function() { 
    return localStorage.getItem("nameKey"); 
    } 
    return traitService; // This is what will be injected above 
}); 
관련 문제