Javascript 用于替换文本的Angularjs指令
我是angularjs的新手,我想创建一个指令来更改文本以供人类阅读 范围包括来自数据库的记录。我想将它们更改为匹配人类可读的数组Javascript 用于替换文本的Angularjs指令,javascript,angularjs,Javascript,Angularjs,我是angularjs的新手,我想创建一个指令来更改文本以供人类阅读 范围包括来自数据库的记录。我想将它们更改为匹配人类可读的数组 angular.module('app', []) .directive("humanReadable", function () { return { restrict: "A", replace: true } }); var 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>
- {{item}-
更好的方法是使用自定义过滤器。您可以在文档或api中阅读有关它的所有信息 您也可以从翻译过滤器中获得一些灵感: 总之,您可能会这样写:
{{item | humanreadable}}
或使用ngbind
这样写:
使用这些工具,我相信您可以找到一些解决方法。更好的方法是使用自定义过滤器。您可以在文档或api中阅读有关它的所有信息
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);
}
});
}
}
});
您也可以从翻译过滤器中获得一些灵感:
总之,您可能会这样写:{{item | humanreadable}}
或使用ngbind
这样写:
使用这些工具,我相信你能想出一些办法
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);
}
});
}
}
});
演示:
演示:正如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; }));
}
};
});
编辑:我没有使用您的HumaReadable数组来概括它,假设您可能会发现它有用,而不是使用单独的数组。正如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数组来概括它,假设您可能会发现它有用,而不是使用单独的数组