Angular Translate与指令一起使用

时间:2014-09-10 16:52:01

标签: angularjs asp.net-mvc-4 angularjs-directive angularjs-scope angular-ui

这是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 file

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;}

1 个答案:

答案 0 :(得分:2)

您无法在指令中使用$ translate提供程序。只需将其作为依赖项注入。如果您想从控制器中删除触发翻译的责任,您可以使用它们作为属性放在您的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;
        });          
    }
  }
]);