directive talks to controller

<!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>

directive指令裏面link參數的scope,可調用外面的方法javascript

修改一下,可用$apply調用方法html

<!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>

再修改一下,可以使用attrs將方法傳進來java

<!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>

這個例子能夠清楚地看到link3個參數的做用app

相關文章
相關標籤/搜索