2014-09-04 103 views
0

我是新的在angularjs,我想创建一个指令,以改变人类可读的文本。Angularjs指令替换文本

范围包括来自数据库的记录。我想改变它们匹配humanReadable数组。

angular.module('app', []) 
    .directive("humanReadable", function() { 
     return { 
      restrict: "A", 
      replace: true 
     } 
    }); 

    var humanReadable= [{ 
     text: "first_name", 
     replace: "First Name" 
    }, 
    { 
     text: "last_name", 
     replace: "Last Name" 
    }]; 

function MyCtrl($scope) { 
    $scope.comesFromDatabase = ["first_name", "last_name"]; 
} 

我的html是这样的。

<div ng-app="app"> 
    <div ng-controller="MyCtrl"> 
     <ul> 
      <li ng-repeat="item in comesFromDatabase">{{item}} - 
       <span human-readable="item"></span> 
      </li> 
     </ul> 
    </div> 
</div> 

jsfiddle is here

回答

0

一个更好的办法是使用自定义过滤器。你可以阅读所有关于它的文档https://docs.angularjs.org/guide/filter或API https://docs.angularjs.org/api/ng/filter/filter 你可能需要一些灵感来自于翻译过滤器太:https://github.com/angular-translate/angular-translate 总之,你可能会写它像这样:{{item | human-readable}}ng-bind像这样:<span ng-bind="item | human-readable">

使用的工具,我敢肯定,你可以想办法的

1
angular.module('app', []) 
    .directive("humanReadable", function() { 
    return { 
     restrict: "A", 
     scope: { 
      items: '=', 
      humanReadable: '=' 
     }, 
     link: function (scope, element, attrs) { 
      scope.items.forEach(function (item, i) { 
       if (item.text === scope.humanReadable) { 
        element.text(item.replace); 
       } 
      }); 

     } 
    } 
}); 

演示:http://jsfiddle.net/moogs/vhbg6104/4/

3

作为Martinspire提到的,最好使用过滤器可能类似于下面 -

angular.module('myapp') 
    .filter('humanReadable', [function() { 
     return function (str) { 
      return str.split("_").join(" ").replace(/([^ ])([^ ]*)/gi,function(v,v1,v2){ return v1.toUpperCase()+v2; }); 

     }; 
    }]); 

如果你想只指令,带着几分修改上面的代码中,它看起来像这样 -

angular.module('myapp') 
     .directive('humanReadable', function() { 
      return { 
       restrict: 'A', 
       link: function (scope, element, attrs) { 
        element.html(attrs.humanReadable.split("_").join(" ").replace(/([^ ])([^ ]*)/gi,function(v,v1,v2){ return v1.toUpperCase()+v2; })); 
       } 
      }; 
     }); 

编辑:我没有使用你的humamReadable数组来推广它,假设你可能会发现它有用而不是使用单独的数组。