angularjs directive2

HTML:

<div ng-app="app">
    <food apple orange water>水果</food>
    <food apple orange>水果</food>
</div>    

JS:

var app = angular.module("app", []);
    app.directive("food", function () {
        return {
            restrict: "E",
            scope: {},      //清空scope
            controller: function ($scope) {
                $scope.foods = [];
                this.addapple = function () { $scope.foods.push("苹果") }
                this.addorange = function () { $scope.foods.push("橘子") }
                this.addwater = function () { $scope.foods.push("西瓜") }
            },
            link: function (scope, element, attrs) {
                element.bind("mouseenter", function () {
                    alert(scope.foods);
                })
            }
        }
    })
    app.directive("apple", function () {
        return {
            require: "food",
            link: function (scope, element, attrs, ctrl) {
                ctrl.addapple();
            }
        }
    })
    app.directive("orange", function () {
        return {
            require: "food",
            link: function (scope, element, attrs, ctrl) {
                ctrl.addorange();
            }
        }
    })
    app.directive("water", function () {
        return {
            require: "food",
            link: function (scope, element, attrs, ctrl) {
                ctrl.addwater();
            }
        }
    })

 

posted on 2018-03-16 15:53  段了的弦  阅读(126)  评论(0编辑  收藏  举报