AngularJS指令和控制器之间怎么交互

我们先看一个简单的代码:

<!doctype html>
<html ng-app="MyModule">
<head>
    <meta charset="utf-8">
</head>
<body>
<div ng-controller="MyCtrl">
    <loader>滑动加载</loader>
</div>
</body>
<script src="framework/angular-1.3.0.14/angular.js"></script>
</html>

<script>
    var myModule = angular.module("MyModule", []);
    myModule.controller('MyCtrl', ['$scope', function ($scope) {
        $scope.loadData = function () {
            console.log("加载数据中...");
        }
    }]);

    myModule.directive("loader", function () {
        return {
            restrict: "AE",
            link: function (scope, element, attrs) {
                element.bind('mouseenter', function (event) {
                    scope.loadData();
                });
            }
        }
    });
</script>

通过link监听鼠标滑动时间,调用控制器loadData方法。

指令的复用

上面的实现方式,只能加载调用指定的控制器,无法进行复用,我们通过属性,来实现调用不同的控制器,来加载不同的数据:

<!doctype html>
<html ng-app="MyModule">
<head>
    <meta charset="utf-8">
</head>
<body>
<div ng-controller="MyCtrl">
    <loader howToLoad="loadData()">滑动加载</loader>
</div>
<div ng-controller="MyCtrl2">
    <loader howToLoad="loadData2()">滑动加载</loader>
</div>
</body>
<script src="framework/angular-1.3.0.14/angular.js"><//script>
</html>

<script>
    var myModule = angular.module("MyModule", []);
    myModule.controller('MyCtrl', ['$scope', function ($scope) {
        $scope.loadData = function () {
            console.log("加载数据中...");
        }
    }]);
    myModule.controller('MyCtrl2', ['$scope', function ($scope) {
        $scope.loadData2 = function () {
            console.log("加载数据中...22222");
        }
    }]);
    myModule.directive("loader", function () {
        return {
            restrict: "AE",
            link: function (scope, element, attrs) {
                element.bind('mouseenter', function (event) {
                    //scope.loadData();
                    // scope.$apply("loadData()");
                    // 注意这里的坑,howToLoad会被转换成小写的howtoload
                    scope.$apply(attrs.howtoload);
                });
            }
        }
    });
<//script>






发表于: 21天前   最后更新时间: 21天前   游览量:75
上一条: AngularJS指令之compile和link
下一条: AngularJS指令之间如何交互

评论…


  • 评论…
    • in this conversation