AngularJS-directive自定义指令与link绑定事件

directive指令,link绑定事件($apply这种方式只需要改变页面的调用方法即可)

/**
 * Created by GrandKai on 29/09/2016.
 */
var app = angular.module("app", []);
app.controller("foodCtrl", function ($scope) {
    $scope.loadMoreData =  function () {
        alert("加载更过数据。。");
    }
    $scope.delData =  function () {
        alert("删除数据。。");
    }
});

app.directive("enter", function () {
    // 只有一个link函数可以直接返回function
    return function (scope, element, attrs) {
        element.bind("mouseenter", function () {
            // scope.$apply("loadMoreData()");
            scope.$apply(attrs.enter);//调用更叫灵活
        });
    }

});

app.directive("food", function () {
    return {
        restrict: "E", // 不写默认是A属性
        template: "hello angular",
        replace:true,//默认false,作用:取代food标签元素(页面不显示)
        scope: {},//需要清空scope
        controller: function ($scope) {
            $scope.foods = [];
            this.addApple = function () {
                $scope.foods.push("apple");
            };
            this.addOrange = function () {
                $scope.foods.push("orange");
            };
            this.addBanana = function () {
                $scope.foods.push("banana");
            }
        },
        link: function (scope, element, attrs) {
            element.bind("mouseenter", function () {
                console.log(scope.foods);
            });
        }
    }
});

app.directive("apple", function () {
    return {
        require: "food",
        // foodCtrl 指向food中定义的controller
        link: function (scope, element, attrs, foodCtrl) {
            foodCtrl.addApple();
        }
    }
});

app.directive("orange", function () {
    return {
        require: "food",
        // foodCtrl 指向food中定义的controller
        link: function (scope, element, attrs, foodCtrl) {
            foodCtrl.addOrange();
        }
    }
});

app.directive("banana", function () {
    return {
        require: "food",
        // foodCtrl 指向food中定义的controller
        link: function (scope, element, attrs, foodCtrl) {
            foodCtrl.addBanana();
        }
    }
});

html代码

<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
    <meta charset="UTF-8">
    <title>todolist</title>
    <script src="js/angular.min.js"></script>
    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
</head>
<body>

<div class="container" ng-controller="foodCtrl">
    <food apple banana orange>所有食物</food>
    </br>
    <food apple banana>所有食物</food>
    </br>

    <div enter>im here1</div>
    </br>
    <div enter="loadMoreData()">im here2</div>
    </br>
    <div enter="delData()">im here3</div>
</div>


<script type="text/javascript" src="food.js"></script>
</body>
</html>
上一篇:查看某个方法的doc


下一篇:Spring Boot 加载properties配置文件