首页 > 其他 > 详细

directive talks to controller

时间:2014-04-23 13:29:50      阅读:454      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
<!DOCTYPE html>
<html ng-app="demo">
<head>
    <title>directive talks to controller</title>
    <script src="angular.min.js" type="text/javascript"></script>
</head>
<body ng-controller="demoController">
    <div enter>{{name}}</div>
</body>
<script>
    var demo = angular.module("demo",[]);
    demo.controller("demoController", function ($scope) {
        $scope.name = "Jackey works hard";
        $scope.show = function () {
            console.log("hei");
        };
    });
    demo.directive("enter", function () {
        return {
            restrict: "A",
            link: function (scope, element, attrs) {
                element.bind("mouseenter", function () {
                    scope.show();
                });
            }
        };
    });
</script>
</html>
bubuko.com,布布扣

directive指令里面link参数的scope,可调用外面的方法

修改一下,可用$apply调用方法

bubuko.com,布布扣
<!DOCTYPE html>
<html ng-app="demo">
<head>
    <title>directive talks to controller</title>
    <script src="angular.min.js" type="text/javascript"></script>
</head>
<body ng-controller="demoController">
    <div enter>{{name}}</div>
</body>
<script>
    var demo = angular.module("demo",[]);
    demo.controller("demoController", function ($scope) {
        $scope.name = "Jackey works hard";
        $scope.show = function () {
            console.log("hei");
        };
    });
    demo.directive("enter", function () {
        return {
            restrict: "A",
            link: function (scope, element, attrs) {
                element.bind("mouseenter", function () {
                    scope.$apply("show()");
                });
            }
        };
    });
</script>
</html>
bubuko.com,布布扣

再修改一下,可使用attrs将方法传进来

bubuko.com,布布扣
<!DOCTYPE html>
<html ng-app="demo">
<head>
    <title>directive talks to controller</title>
    <script src="angular.min.js" type="text/javascript"></script>
</head>
<body ng-controller="demoController">
    <div enter="show()">{{name}}</div>
</body>
<script>
    var demo = angular.module("demo",[]);
    demo.controller("demoController", function ($scope) {
        $scope.name = "Jackey works hard";
        $scope.show = function () {
            console.log("hei");
        };
    });
    demo.directive("enter", function () {
        return {
            restrict: "A",
            link: function (scope, element, attrs) {
                element.bind("mouseenter", function () {
                    scope.$apply(attrs.enter);
                });
            }
        };
    });
</script>
</html>
bubuko.com,布布扣

这个例子可以清楚地看到link3个参数的作用

directive talks to controller,布布扣,bubuko.com

directive talks to controller

原文:http://www.cnblogs.com/lihaozhou/p/3681946.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!