angularjs 自定义: (过滤器,指令,服务)

来源:互联网 发布:c语言是什么 编辑:程序博客网 时间:2024/05/21 10:20
自定义指令
通过添加 restrict 属性,并设置值为 "A", 来设置指令只能通过属性的方式来调用:
var app = angular.module("myApp", []);
app.directive("runoobDirective", function() {
return {
restrict : "A",
template : "<h1>自定义指令!</h1>"
};
});

<div runoob-directive></div>

restrict 值可以是以下几种:
  • E 作为元素名使用
  • A 作为属性使用
  • C 作为类名使用
  • M 作为注释使用
restrict 默认值为 EA, 即可以通过元素名和属性名来调用指令。


自定义过滤器(现有项目里 app 要替换成 myApp 并且放在 app.controller 外)
app.filter('reverse', function() { //可以注入依赖
return function(text) {
return text.split("").reverse().join("");
}
});

{{ msg | reverse }}

自定义服务
app.service('hexafy'function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});

使用自定义的的服务 hexafy 将一个数字转换为16进制数:
app.controller('myCtrl'function($scope, hexafy) {
    $scope.hex = hexafy.myFunc(255);
});

在过滤器 myFormat 中使用服务 hexafy:
app.filter('myFormat',['hexafy'function(hexafy) {
    return function(x) {
        return hexafy.myFunc(x);
    };
}]);

angularjs 可以 copy对象
$scope.master = {firstName: "John", lastName: "Doe"};
$scope.user = angular.copy($scope.master);

























原创粉丝点击