-1

這裏是fiddle link ....我試圖用$ translate更新指令的內容並使用控制器。是否有任何其他通用的方式來做同樣的事情(鏈接在指令?)。如果我想在一個控制器中使用相同的指令,那麼這種方法可能無法正常工作。 基本上我怎麼擺脫控制器?角度翻譯使用指令

HTML

<terms-conditions conditions="conditions" checked="checked"></terms-conditions> <br> 
    <button class="btn-primary" ng-disabled="!checked" >Submit</button> 
     <hr> 


</div> 

    <div name="info" ng-controller="myCtrl2"> 
<terms-conditions conditions="conditions" checked="checked"></terms-conditions> <br> 
     <button class="btn-primary" ng-disabled="!checked">Submit</button> 
     <hr> 

</div> 
</div> 

JS文件

var demo = angular.module('demo', ['pascalprecht.translate']); 
demo.directive("termsConditions",function(){ 
return { 
    restrict:"E", 
    scope:{ 
     conditions:'=', 
     checked:'=' 
    }, 
    template: 
    "<div class='terms row'><span class='col-md-12'>{{conditions}}</span></div><br><input type='checkbox' ng-model='checked'><span>Yes, I agree to the terms and condtions</span>" 
} 

}); 
demo.config(function ($translateProvider) { 
    $translateProvider.translations('en', { 
     PRODUCT_NAME: 'NAME', 
     TERMS_CONDITIONS:"TERMS & CONDITIONS", 
     OTHER_TERMS_CONDITIONS: 'OTHER TERMS & CONDITIONS', 
     AGREEMENT: 'Yes, I agree to the terms and condtions ', 

    }); 

    $translateProvider.preferredLanguage('en'); 

}) 
demo.controller("myCtrl1", function ($scope, $translate) { 
$translate('TERMS_CONDITIONS') 
    .then(function (translatedValue) { 
     $scope.conditions = translatedValue; 
    }); 

}) 
demo.controller("myCtrl2", function ($scope, $translate) { 
$translate('OTHER_TERMS_CONDITIONS') 
    .then(function (translatedValue) { 
     $scope.conditions = translatedValue; 
    }); 

}) 

CSS

span { 
font-weight:bold; 
} 
.terms{font-weight: normal; 
width: 500px; 
height: 50px; 
overflow-y: scroll; 
padding: 5px 5px 5px 5px; 
border-style: solid; 
border-color: #666666; 
border-width: 1px;} 

回答

2

沒有理由你不能使用$您的指令翻譯提供商。只需將它注入爲依賴項即可。如果你想從控制器中取出觸發翻譯的責任,你可以在html中使用這些屬性。

例(沒有測試,但是這是緊挨什麼應該工作):

的HTML(概括指令簡單地使用你每翻譯元素想要的任何標記的屬性和使用)

<div translated="TERMS_CONDITIONS">{{text}}</div> 

該指令(創建一個新的範圍,使用翻譯服務,並綁定到你把任何值轉換屬性)

demo.directive("translated",['$translate', '$scope', function($translate, $scope){ 
    return { 
    restrict:"AEC", 
    scope:true, 
    link: function(scope, el, attr){ 
     $scope.text = ''; 
     $translate('TERMS_CONDITIONS') 
     .then(function (translatedValue) { 
      $scope.conditions = translatedValue; 
     });   
    } 
    } 
]); 
+0

感謝卡爾文:)其實我得到了同樣的方式。抱歉忘記在這裏附上解決方案。 – future 2014-09-11 04:23:55

+0

請不要忘記標記爲接受的答案。 – 2014-09-11 04:33:33