您的位置:首页 > Web前端 > HTML5

html5_依赖注入的5个重要的组件

2017-10-16 18:37 211 查看
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="angular-1.3.0.js"></script>
<script>
// 依赖注入:5个重要的组件factory、provider、service、value、constant
var app = angular.module("myapp", []);
//第一种factory
//        app.factory("calculator", function () {
//            return {
//                add: function (a, b) {
//                    return a + b;
//                },
//
//                subtract: function (a, b) {
//                    return a - b;
//                },
//
//                multiply: function (a, b) {
//                    return a * b;
//                },
//
//                divide: function (a, b) {
//                    if (b != 0) {
//                        return a / b;
//                    }
//                    return 0;
//                }
//            };
//        });

//第二种provider
//        app.provider("calculator",function(){
//            this.$get = function(){
//                return {
//                add: function (a, b) {
//                    return a + b;
//                },
//
//                subtract: function (a, b) {
//                    return a - b;
//                },
//
//                multiply: function (a, b) {
//                    return a * b;
//                },
//
//                divide: function (a, b) {
//                    if (b != 0) {
//                        return a / b;
//                    }
//                    return 0;
//                }
//                }
//            }
//        });

//第三种service  单例
app.service("calculator",function(){
this.add = function (a, b) {
return a + b;
};

this.subtract = function (a, b) {
return a - b;
};

this.multiply = function (a, b) {
return a * b;
};

this.divide = function (a, b) {
if (b != 0) {
return a / b;
}
return 0;
}
});

//value
//        app.value("a", "除数不能等于零!");
//        app.value("a", "除数不能等于零!!!!!");
//        app.controller("myCtrl", function ($scope, a) {
//            //输出的是 "除数不能等于零!!!!!" 下面覆盖了
//            console.log(a);
//        });

//constant
app.constant("a", "除数不能等于零!");
app.constant("a", "除数不能等于零!!!!!");
app.controller("myCtrl", function ($scope, a) {
//输出的是 "除数不能等于零!" 下面没有覆盖
console.log(a);
});

app.controller("myCtrl", function ($scope, calculator) {
//赋值    calculator是方法的第一个参数
$scope.result1 = calculator.add(8, 4);
$scope.result2 = calculator.subtract(8, 4);
$scope.result3 = calculator.multiply(8, 4);
$scope.result4 = calculator.divide(8, 4);
});
</script>
</head>
<body ng-app="myapp">
<div ng-controller="myCtrl">
<div>8 + 4 = {{ result1 }}</div>
<div>8 - 4 = {{ result2 }}</div>
<div>8 * 4 = {{ result3 }}</div>
<div>8 / 4 = {{ result4 }}</div>
</div>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: