-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