Angular小工程,实现图书的增删改($scope)

本文介绍了一个使用Angular和Bootstrap构建的图书管理应用,展示了如何实现图书的增删改查功能,并通过自定义过滤器美化显示。

html部分,用bootstrap定义样式

<!DOCTYPE html>
<html lang="en"  >
<head>
    <meta charset="UTF-8">
    <title>图书增删改</title>
    <link href="css/bootstrap.css" rel="stylesheet">
    <script src="script/angular.min.js"></script>
    <script src="script/books.js"></script>
 </head>
<body ng-app="myApp" ng-controller="userCtrl">
<div class="container">
        <h1>图书列表</h1>
        <table class="table table-striped">
        <thead>
        <tr>
            <th>编辑</th>
            <th>商品名称</th>
            <th>价格</th>
            <th>数量</th>
        </tr>
        </thead>
        <tbody>
        <tr ng-repeat="book in books" >
            <td>
            <button class="btn btn-danger" ng-click="delete(book)" >删除</button>
            <button class="btn btn-warning" ng-click="edit(book)">编辑</button>
        </td>
            <td>{{ book.bName | bookmark}}</td>
            <td>{{ book.bPrice| currency:'¥'}}</td>
            <td class="col-xs-1">
                <input type="number" class="form-control" min="1" max="10" ng-model="book.bNum" ng-disabled="book.noedit"/>
            </td>
        </tr>
        </tbody>
        </table>
    <div class="pull-left">
        <button  class="btn btn-success" ng-click="save()"  ng-disabled="nosave">保存</button>
    </div>
        <div class="pull-right" >
        <label class="btn btn-info">合计</label>
            <label>{{totalPrice() |currency:'¥'}}</label><br>
        </div>


<div class="clearfix"></div>
<hr>
<div class="form-group">
<button class="btn btn-success" ng-click="addBook()" ng-disabled="bookform.$invalid">
添加新图书
</button>
</div>
    <form name="bookform" class="form-horizontal col-md-2">
        <div class="form-group">
         <label>图片名称:</label>
         <input type="text" class="form-control" required ng-model="bName" ng-disabled="!edit" >
        </div>
        <div class="form-group">
        <label>价格:</label>
            <input type="text" class="form-control" required ng-model="bPrice"/>
        </div>
        <div class="form-group">
            <label>数量:</label>
            <input type="number" class="form-control" min="1" max="10" required ng-model="bNum"/>
        </div>
    </form>
</div>


</body>
</html>

js部分

var booklist = [
{id:1, bName:'HTML5+CSS3从入门到精通(附光盘)',bPrice:59.5,bNum:1,noedit:true },
{id:2, bName:'HTM5权威指南',bPrice:112.10,bNum:1,noedit:true},
{id:3, bName:'响应式web设计',bPrice:42.60,bNum:2,noedit:true},
{id:4, bName:'深入理解HTML5',bPrice:55.60,bNum:1,noedit:true},
{id:5, bName:'JavaScript高级编程',bPrice:33.70,bNum:1,noedit:true },
{id:6, bName:'锋利的jQuery',bPrice:28.90,bNum:1,noedit:true }
];
var app = angular.module('myApp', []);
//自定义书名号过滤器
app.filter('bookmark', function(){
    return function(item){
        return "《" + item + "》";        
        }   
    });

//创建控制器
app.controller('userCtrl', function($scope) {
$scope.bName = '';
$scope.bPrice = '';
$scope.tPrice = 0;
$scope.nosave = true;
$scope.books = booklist;
//删除图书
$scope.delete = function(book) {
$scope.books.splice($scope.books.indexOf(book), 1);
};
//编辑图书
$scope.edit = function(book){
    $scope.nosave = false;
    book.noedit = false;

    };
//保存修改
$scope.save = function(){
    $scope.nosave = true;
    angular.forEach($scope.books,function(data){   
        data.noedit = true;
        });
    };

//添加图书
$scope.addBook = function(){
 if(!isNaN(parseFloat($scope.bPrice))){
var i = $scope.books.length;
$scope.bPrice= parseFloat($scope.bPrice); //将价格转换为浮点数
$scope.books.push({id:i, bName:$scope.bName,bPrice:$scope.bPrice,bNum:$scope.bNum,noedit:true });
$scope.bName = "";
$scope.bPrice = "";
} 
};
//计算总价
$scope.totalPrice = function(){
var sum = 0;
angular.forEach($scope.books, function(data){
    sum = sum + data.bPrice*data.bNum;
    });
return sum;
}

});
AngularJS(即 Angular 1.x)中,`$scope.$broadcast()` 是用于向下广播事件到所有子作用域的方法。它是 `$scope` 提供的一种事件传播机制,常用于父子组件之间的通信。 --- ## 📌 `$scope.$broadcast` 的作用 - **从父级作用域向所有子作用域广播事件**。 - 子作用域可以通过 `$on` 监听这个事件并做出响应。 - 不会影响父级及以上的作用域。 --- ## ✅ 示例代码 ### 父控制器广播事件: ```javascript app.controller('ParentCtrl', function($scope) { $scope.broadcastMessage = function() { // 广播一个名为 'customEvent' 的事件,并携带数据 $scope.$broadcast('customEvent', { message: 'Hello from parent!' }); }; }); ``` ### 子控制器监听事件: ```javascript app.controller('ChildCtrl', function($scope) { $scope.$on('customEvent', function(event, data) { console.log('收到广播:', data.message); // 输出:Hello from parent! }); }); ``` ### HTML 结构: ```html <div ng-controller="ParentCtrl"> <button ng-click="broadcastMessage()">广播消息</button> <div ng-controller="ChildCtrl"> <p>这里是子控制器,可以监听广播事件。</p> </div> </div> ``` --- ## 🔁 对比 `$broadcast`, `$emit`, `$on` | 方法 | 作用方向 | 描述 | |----------------|-----------------------|------| | `$broadcast` | 向下(子作用域) | 从当前作用域向所有子作用域广播事件 | | `$emit` | 向上(父作用域) | 从当前作用域向上传递给父作用域 | | `$on` | 监听事件 | 接收由 `$broadcast` 或 `$emit` 发出的事件 | --- ## ⚠️ 注意事项 1. **避免滥用事件通信**: - 过度使用 `$broadcast` 和 `$emit` 会使应用难以维护和调试。 - 推荐优先使用服务(Service)或指令间通信等方式实现更清晰的交互。 2. **手动清理事件监听器**: - 在控制器销毁时,最好手动移除 `$on` 监听器以防止内存泄漏。 ```javascript var deregisterFn = $scope.$on('customEvent', function() { // 处理逻辑... }); // 在适当的时候取消注册 deregisterFn(); ``` 3. **性能问题**: - `$broadcast` 会遍历所有子作用域,如果结构复杂且频繁调用,可能影响性能。 --- ## ✅ 应用场景 - 表单重置通知 - 全局状态变更通知(如用户登录) - 页面刷新、加载状态更新 - 多个嵌套组件需要同步数据时 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值