AngularJS 学习笔记 05:自定义服务(factory、service、value / constant、provider)

factory 方式

  • 使用 factory 方法创建服务
var app = angular.module('App', []);
app.controller('demoCtrl', ['$scope', 'firstUp', 'toPath', function($scope, firstUp, toPath){

    $scope.obj = {
        name: 'hannah',
        sex: 'woman',
        age: 18
    }

    console.log(firstUp($scope.obj.name)); // => Hannah
    console.log(toPath.format($scope.obj)); // => name=hannah&sex=woman&age=18
}])

//使用 factory 自定义服务 - 首字母大写
app.factory('firstUp', ['$filter', function($filter){
    return function(str) {
        return str[0].toUpperCase() + str.slice(1);
    }
}])

//使用 factory 自定义服务 - 转 get 传值格式
app.factory('toPath', ['$filter', function($filter){
    return {
        format:format
    }

    function format(arg){    //暴露一个函数出去
        var str = ""
        for(var key in arg){
            str += key + '=' + arg[key] + '&';
        }
        return str.slice(0,-1);
    }

}])

service 方式

  • 使用 service 方法创建服务
var app = angular.module('App', []);
app.controller('demoCtrl', ['$scope', 'str', function($scope, str){

    $scope.name = 'hannah';

    // 调用自定义服务 str 下的 firstUp 方法
    var toA = str.firstUp($scope.name)

    console.log(toA); // => Hannah
}])

App.service('str',['$filter', function($filter){    

    this.firstUp = function(inp){
        return inp[0].toUpperCase() + inp.slice(1);
    }

}])

value / constant 方式

  • 使用 constantvalue 方法创建服务,常用于返回一个常量
<html ng-app="App">
    <div ng-controller="demoCtrl">
        <p>作者:{{author}}</p> <!-- => hannah -->
        <p>版本:{{version}}</p> <!-- => 1.0.0 -->
    </div>
</html>
var app = angular.module("App",[]);

app.controller('demoCtrl', ['$scope', 'author', 'version', function($scope, author, version){
    $scope.author = author;
    $scope.version = version;
}])

app.value('author','hannah');
app.value('version','1.0.0');

provider 方式

猜你喜欢

转载自blog.csdn.net/wildye/article/details/80098844
今日推荐