如何通过$ translate观察角度指令的变化

时间:2014-09-15 00:20:45

标签: angularjs angularjs-directive angularjs-scope

这是Fiddle Link

我如何注意指令的变化?在这个小提琴示例中使用$ translate来翻译内容。除了指令中的内容外,所有内容都会发生变化。

HTML看起来像这样 -

 <div ng-app='demo'>

<div name="info" ng-controller="myctrl">
    <label translate="TERMS_LABEL"></label>
    <h4 translate="ZIPCODE_LABEL"></h4>
    <p translate="LAST_NAME"></p>
   <terms-conditions conditions="TERMS_CONDITIONS" checked="checked"></terms-conditions> 
    <button type="submit"  ng-click="changeLanguage('de')" >Spanish</button>
     <button type="submit"  ng-click="changeLanguage('en')" >English</button>

     </div>

指令看起来像

 demo.directive("termsConditions",['$translate',function($translate){
return {
    restrict:"E",
    scope:{
         checked:'='
    },
    link: function(scope, element, attr) { 
        $translate(attr.conditions)
        .then(function (translatedValue) {
            scope.conditions = translatedValue;
        });
    },
    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>"
}

}]);

1 个答案:

答案 0 :(得分:1)

您是否有理由无法在模板中进行翻译?

http://jsfiddle.net/UGLjh/75/

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

}]);

如果您知道您的属性不会被插值,则无需使用$observe;只是把它放在范围上就像这样:

    link: function(scope, element, attr) { 
        scope.conditions = attr.conditions;
    },