在Angular.js中,双向数据绑定不能用于指令

Two-way data binding does not work with directives in Angular.js

本文关键字:数据绑定 不能 用于 指令 Angular js      更新时间:2023-09-26

我尝试实现一个指令,它必须用angular符号{{…}}更新特定的代码块。问题是更新后的代码不再编译。

指令:

.directive('i18n', [function() {
'use strict';
return function(scope, element) {
        var bindLabel = '{{labels.' + element.text() + '}}',
        //create an empty object
        obj = {
        };
        obj[element.text()] = '';
        //extend the labels
        angular.extend(scope.labels, obj);
        element.text(bindLabel);
};
}])
简单的HTML代码:
<title i18n>title</title>
编译后的HTML代码:
<title i18n="">{{labels.title}}</title>
所需输出:

 <title i18n="">This is my title :)</title>

{{labels.title}}在控制器中实现。

谢谢你的帮助!

使用$compile服务动态编译DOM元素:

element.html(value);
// Compile the new DOM and link it to the current scope
$compile(element.contents())(scope);

在你的例子中,它看起来像这样:

.directive('i18n', [ '$compile', function($compile) {
'use strict';
return function(scope, element) {
        var bindLabel = '{{labels.' + element.text() + '}}',
        //create an empty object
        obj = {
        };
        obj[element.text()] = '';
        //extend the labels
        angular.extend(scope.labels, obj);
        // Fill element's body with the template
        element.html(bindLabel);
        // Compile the new element and link it with the same scope
        $compile(element.contents())(scope);
    };
}]);

您可以在这里找到更多信息:http://docs.angularjs.org/api/ng.$compile

请注意,只要你不自己使用$compile, AngularJS模板只在应用程序引导时编译一次。

AngularJS编译和链接阶段

要理解为什么你的代码不工作,你必须了解AngularJS的编译和链接阶段。一旦你加载了应用,AngularJS就会用$compile服务编译包含ng-app属性的HTML元素,例如

<html ng-app="MyApp"></html>

编译阶段

$compile标识HTML模板中的所有指令,调用每个指令的编译函数,从你的angular根元素($rootElement)开始,沿着HTML dom树往上爬。

链接阶段

每个编译函数返回一个后链接函数和一个可选的预链接函数。一旦AngularJS编译完根元素以下的整个dom,它就会开始调用pre-link函数,就像之前调用compile函数一样。一旦到达dom的叶子,指令的post-link函数就会被调用,返回到根元素。

插值

表达式在{{和}}之间的字符串由AngularJS作为特殊指令处理,称为插值指令。就像其他指令一样,这些指令是在编译过程中使用$interpolate服务创建的。$interpolate服务接收带有多个表达式的插入字符串,并返回一个插入函数。interpolate指令的post-link函数会对interpolate函数进行监视,以便一旦插入字符串中的任何表达式发生变化,它们就可以更新html节点。

翻译模块

当我们现在看你的代码时,你实际上是把一个html元素的文本设置为一个AngularJS插值字符串,并在你指令的post-link函数中包装了一个表达式在{{和}}之间。

如上所述,此时AngularJS已经编译了模板,所以它永远不会用你的表达式编译插入的字符串。

我可以从你的代码中看到,你正试图实现某种翻译指令。这样的指令必须调用$compile函数,当它应该考虑插入字符串和其他AngluarJS模板代码在翻译字符串:

directive('translate', ['$compile','translate', function factory($compile, translate) { 
    return {            
        priority: 10, // Should be evaluated before e. g. pluralize
        restrict: 'ECMA',
        link: function postLink(scope, el, attrs) {
            if (el.contents().length) {
                el.html(translate(el.text()));
                $compile(el.contents())(scope); // This is only necessary if your translations contain AngularJS templates
            }
        },
    };
}]).

translate指令使用翻译服务来获取实际的翻译。translateProvider有一个add方法,你可以用它来添加翻译,比如从一个语言包中:

.provider('translate', function() {
    var localizedStrings = {};
    var translateProvider = this;
    this.add = function(translations) {
        angular.extend(localizedStrings, translations);
    };
    this.$get = ['$log', '$rootScope', function ($log, $rootScope) {
        var translate = function translate(sourceString) {            
            if (!sourceString) {
                return '';
            }
            sourceString = sourceString.trim();
            if (localizedStrings[sourceString]) {
                return localizedStrings[sourceString];
            } else {
                $log.warn('Missing localization for "' + sourceString + '"');
                return sourceString;
            }
        };
        return translate;
    }];    
}).
config(function(translateProvider) {
    translateProvider.add({'My name is {{name}}': 'Mi nombre es {{name}}'}); // This might come from a bundle
}).

使用模块

你现在可以这样使用这个模块:

<div ng-app="myApp" ng-controller="MyCtrl">
    <span data-translate>My name is {{name}}</span>
</div>

我已经创建了一个jsFiddle的完整示例:http://jsfiddle.net/jupiter/CE9V4/2/

另外,对于翻译,我推荐http://github.com/pascalprecht/angular-translate.

我认为$compile可能是你正在寻找的。试一试:

var bindLabel = $compile('{{labels.' + element.text() + '}}')(scope);