Using directives inside directives causes binding issues

最后都变了- 提交于 2019-12-13 03:41:27

问题


We're using Angular and we're having trouble with resolving variables in directives. This fiddle shows our issue:

Here's the full code: http://jsfiddle.net/VX5LE/65/

//data-translate should handle the translating of the useableButton text
app.directive('window', ['translateService', function (translateService) {

    return {
        restrict: 'E',
        transclude: true,
        scope: {
            useableButtons: '='},
        replace: true,
        template:
                '<div>' +
                    '<button data-ng-repeat="useableButton in useableButtons" data-translate>{{useableButton}}</button>' +
            '</div>'
    };
}]);

I have seen some answers that solve this by:

  1. Using a filter to translate these. - That is actually our current solution but that hinders us with different functionality.

  2. Attaching watches in the controller. - We actually want to avoid watches in our controllers as it makes the code quite dirty if you have a lot of them.

Preferably I would like to see a solution that resides inside of the translate directive without cluttering the controllers.


回答1:


You can do this by interpolating the values manually, then parsing it with the $eval function of the desired scope.

Here is the fiddle: http://jsfiddle.net/VX5LE/66/

The code of the translate-directive:

app.directive('translate', ['translateService', '$interpolate', function (translateService, $interpolate) {
  return {
      restrict: 'A',
      link: function (scope, element, attrs) {
          var pHTML = element.html();
          var parsed = $interpolate(pHTML);
          var translated_result = translateService.translate(scope.$eval(parsed));
          element.text(translated_result);
      }
  }
}]);


来源:https://stackoverflow.com/questions/16358706/using-directives-inside-directives-causes-binding-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!