zoukankan      html  css  js  c++  java
  • angularJS1笔记-(13)-自定义指令(controller和controllerAs实现通信)

    index.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
    <div ng-app="myApp">
        <div  ng-controller="firstController">
            <div book-list></div>
        </div>
    </div>
    
    <script type="text/javascript" src="../../vendor/angular/angularJs.js"></script>
    <script type="text/javascript" src="app/index.js"></script>
    
    <script>
    </script>
    
    </body>
    </html>
    

      index.js:

    var myApp = angular.module('myApp', [])
        .directive('bookList', function () { //bookList对应view层的book-list
            return {
                restrict: 'ECAM',
                controller: function ($scope) {
                    $scope.books = [
                        {
                            name: 'php'
                        },
                        {
                            name: 'js'
                        },
                        {
                            name: 'java'
                        }
                    ];
                    this.addBook = function () {
                        //$scope.$apply为全局刷新 在更新完model层数据源$scope.books后也要刷新view层显示
                        $scope.$apply(function () {
                            $scope.books.push({
                                name:'iOS'
                            })
                        })
                    }
                },
                controllerAs: 'bookListController', //起一个别名
                template: '<div><ul><li ng-repeat="book in books">{{book.name}}</li></ul><book-add></book-add></div>',
                replace: true
            }
        })
        .directive('bookAdd',function () {
            return{
                restrict:'ECAM',
                require:'^bookList',//^代表向上找标签约束<book-add></book-add>
                template:'<button type="button">添加</button>',
                replace:true,
                link:function (scope, iElement, iAttrs, bookListController) {//把controllerAs: 'bookListController' 注入进来
                    iElement.on('click',bookListController.addBook);
                }
            }
        })
        .controller('firstController', ['$scope', function ($scope) {
               //代表当前是给firstController服务的
        }]);
    

      运行结果:

  • 相关阅读:
    vue自定义指令使用注意事项
    es6新增方法---实用
    webpack和gulp的区别
    OSI 5层协议,socket,从协议角度看网络通信
    网络通信流程
    数据相关的模块
    一些模块
    面向对象
    ATM作业
    XML模块增删改查基本操作
  • 原文地址:https://www.cnblogs.com/yk123/p/6887019.html
Copyright © 2011-2022 走看看