AngulatJS $directive

restrict : E/A/C/M 绑定元素的类型 E element A attribute C class M comment

template: 返回的string

replace :是否去掉外层wrap

controller 内置的控制器

简单例子:

<!DOCTYPE html>

<html ng-app="demo">
<head>
    <title></title>
    <script src="angular.min.js" type="text/javascript"></script>
</head>
<body>
    <div my-Directive></div>
</body>
<script>
    var demo = angular.module("demo", []);
    demo.controller("demoController", function ($scope) {

    });
    demo.directive("myDirective", function () {
        return {
            restrict: "A",
            replace: true,
            controller: function ($scope) {
                $scope.name = "click me";
            },
            template: "<a href=‘http://google.com‘>{{name}}</a>"
        };
    });
</script>
</html>

 directive 与DOM交互的理解可以通过scope来传递

<!DOCTYPE html>

<html ng-app="demo">
<head>
    <title></title>
    <script src="angular.min.js" type="text/javascript"></script>
</head>
<body>
    <div my-Directive my-Url="http://google.com" my-Text="click me"></div>
</body>
<script>
    var demo = angular.module("demo", []);
    demo.controller("demoController", function ($scope) {

    });
    demo.directive("myDirective", function () {
        return {
            restrict: "A",
            replace: true,
            controller: function ($scope) {
                //$scope.name = "click meee";
            },
            scope:{
                myUrl:"@",
                myText:"@"
            },
            template: "<a href=‘{{myUrl}}‘>{{myText}}</a>"
        };
    });
</script>
</html>

 

 

 再看另外一个例子

<!DOCTYPE html>

<html ng-app="demo">
<head>
    <title></title>
    <script src="angular.min.js" type="text/javascript"></script>
</head>
<body>
    <input type="text" ng-model="theirUrl" />
    <div my-Directive my-Url="http://google.com" my-Text="click me" some-Attr="theirUrl"></div>
</body>
<script>
    var demo = angular.module("demo", []);
    demo.controller("demoController", function ($scope) {

    });
    demo.directive("myDirective", function () {
        return {
            restrict: "A",
            replace: true,
            controller: function ($scope) {
                //$scope.name = "click meee";
            },
            scope:{
                myUrl:"=someAttr",//modified
                myText:"@"
            },
            template: "<a href=‘{{myUrl}}‘>{{myText}}</a>"
        };
    });
</script>
</html>

用theirUrl将some-Attr关联起来,通过scope传递值进去directive

AngulatJS $directive,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。