继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

angularjs指令中实现与外层组件进行数据交互的几种方式

PIPIONE
关注TA
已关注
手记 1078
粉丝 147
获赞 702

指令中实现与外层组件进行数据交互大概有这几种方式:

* 和父级作用域共用一个scope(双向绑定/双向传递)
* 继承父级作用域的scope(单向绑定/单向传递)
* 通过事件监听来进行传递数据(/单向传递)
* 通过指令中link函数中attr进行获取父级数据(单向传递)
* 通过指令中scope:{  }中@进行获取父级数据(单向传递)
* 通过指令中scope:{  }中“=”进行传递数据(双向绑定)
* 通过$scope.$watch()进行数据监听进行数据传递(单向绑定)
* 通过$scope.$observe()进行数据监听进行数据传递(单向绑定)
* 指令通过require:'ngModel'进行数据传递(双向绑定)
通过下面例子来解释一下<p>

通过指令中<code>scope:{  }</code>中“=”进行传递数据(双向绑定)

先放代码,然后解释

<body ng-controller="myCon">    <div ng-repeat="option in data">
        <h3>{{option.tittle}}</h3>
        <h2>{{option.content}}</h2>
        <em-text data="option.content"></em-text>
    </div></body>
var app=angular.module("interpolateApp",["template"])
            .controller("myCon",["$scope", function ($scope) {
                $scope.data=[{                    tittle:"one",                    content:"123"
                },{                    tittle:"two",                    content:"444"
                },{                    tittle:"three",                    content:"555"
                }]
            }])
            .directive("emText", function () {                return{                    restrict:'E',                    templateUrl:'test.html',                    replace:true,                    scope:{                        data:'='
                    },                    link: function (scope, element, attrs) {                        //var num=parseInt(attrs.data);
                        var num=scope.data;                        /*console.log(num);*/
                        if(num>500){
                            scope.isActive=true
                        }else{
                            scope.isActive=false;
                        }
                    }
                }
            })var template=angular.module("template",[])
    .run(["$templateCache", function ($templateCache) {
        $templateCache.put("test.html","<div>" +            "<span ng-class=\"{true:'active', false:'unActive'}[isActive]\"><input type='text' ng-model='data'/>             </span>" +    "</div>")
}])

这是通过在scope中设置使用场景‘=’来进行数据交互的。其中‘=’的含义是通过与父scope中的属性进行双向绑定。在上例子中即为data属性的值,与指令模板中的ng-model的值进行双向交互。<p>
上面的例子稍加变形就能实现:通过指令中link函数中attr进行获取父级数据(单向传递)

通过指令中link函数中attr进行获取父级数据(单向传递)

代码如下:

<body ng-controller="myCon">    <div ng-repeat="option in data">
        <h3>{{option.tittle}}</h3>
        <h3>{{option.content}}</h3>
        <em-text data="{{option.content}}"></em-text>
    </div></body>
<script>    var app=angular.module("interpolateApp",["template"])
            .controller("myCon",["$scope", function ($scope) {
                $scope.data=[{                    tittle:"one",                    content:123
                },{                    tittle:"two",                    content:544
                },{                    tittle:"three",                    content:455
                }]
            }])
            .directive("emText", function () {                return{                    restrict:'EA',                    templateUrl:'test.html',                    replace:true,                    link: function (scope, element, attrs) {                        var num=attrs.data;                        console.log(num);                        if(num>500){
                            scope.isActive=true
                        }else{
                            scope.isActive=false;
                        }
                        scope.data=num;
                    }
                }
            })    var template=angular.module("template",[])
            .run(["$templateCache", function ($templateCache) {
                $templateCache.put("test.html","<div>" + "<span ng-class=\"{true:'active', false:'unActive'}[isActive]\">{{data}}</span>" + "</div>")
        }])
</script>

案例1和案例2主要有以下几点不同:

<ul>
<li>在html中案例1采用的是data=“option.content”的写法,而案例2采用的是data=“{{option.content}}”这样的写法,因为这是因为案例1是采用scope中‘=’的使用场景,其底层实现原理是<code>$scope.$watch()</code>,<code>$scope.$watch()</code>是实现双向绑定的基础函数,用来监听值的变化,所以不需要写<code>{{}}</code>,但是案例2中是采用通过link函数的attrs来获取属性的值,需要<code>data=“{{option.content}}”</code>首先获取model的中值,然后在传递到<code>link</code>函数中,所以需要写<code>$scope.$watch()</code><li>
<li>通过属性集合<code>attrs</code>来获取其中一个的值。</li>
</ul>

通过指令中scope:{  }中@进行获取父级数据(单向传递)

<!DOCTYPE html><html lang="en" ng-app="connectApp"><head>
    <meta charset="UTF-8">
    <title></title>
    <script src="lib/angular.min.js" type="text/javascript"></script>
    <script src="lib/angular-animate.js" type="text/javascript"></script>
    <style>
        .active{            color:red
        }        .unActive{            color:blue
        }    </style></head><body ng-controller="myCon">
    <div ng-repeat="option in data">
        <h3>{{option.tittle}}</h3>
        <h1>{{option.content}}</h1>
        <em-text data="{{option.content}}"></em-text>
    </div></body><script>
    var app=angular.module("connectApp",["template"])
            .controller("myCon",["$scope", function ($scope) {
                $scope.test=1;
                $scope.data=[{
                    tittle:"one",
                    content:123
                },{
                    tittle:"two",
                    content:544
                },{
                    tittle:"three",
                    content:455
                }]
            }])
            .directive("emText", function () {                return{
                    restrict:'EA',
                    replace:true,
                    templateUrl:"one.html",
                    scope:{
                        data:"@"
                    },
                    link: function (scope, element, attr) {                        if(attr.data>300){
                            scope.isActive=true
                        }else{
                            scope.isActive=false;
                        }
                    }
                }
            })    var template=angular.module("template",[])
        .run(["$templateCache", function ($templateCache) {
            $templateCache.put('one.html',"" +            "<div ng-model=\"data\"  ng-class=\"{true:'active', false:'unActive'}[isActive]\">{{data}}</div>")
        }])</script></html>

在这个案例中使用的是<code>scope{data:"@"}</code>来实现指令与外界进行通信的,此时使用<code>@</code>传递的是字符串而不是对象。即使用当前指令中的template子级scope作用域相同的名称的值,等于父级作用域中和属性名称相同的值。

继承父级作用域的scope(单向绑定/单向传递)

下面是例子

<!DOCTYPE html><html lang="en" ng-app="connectApp"><head>
    <meta charset="UTF-8">
    <title></title>
    <script src="lib/angular.min.js" type="text/javascript"></script>
    <style>
        .active{            color:red
        }        .unActive{            color:blue
        }    </style></head><body ng-controller="myCon"><div ng-repeat="option in data">
    <h3>{{option.tittle}}</h3>
    <h1>{{option.content}}</h1>
    <em-text data="{{option.content}}"></em-text></div></body><script>
    var app=angular.module("connectApp",["template"])
            .controller("myCon",["$scope", function ($scope) {
                $scope.data=[
                    {
                        tittle:"one",
                        content:123
                    },
                    {
                        tittle:"two",
                        content:111
                    },
                    {
                        tittle:"three",
                        content:444
                    }
                ]
            }])
            .directive('emText', function () {                return{
                    restrict:'EA',
                    scope:true,
                    templateUrl:"one.html",
                    link: function (scope, element, attr) {

                    }
                }
            })    var template=angular.module("template",[])
            .run(["$templateCache", function ($templateCache) {
                $templateCache.put("one.html","" +                    "<div da=\"data\" ng-class=\"{true:'active',false:'unActive'}[isActive]\">{{data}}</div>")
            }])</script></html>

如果要创建一个能够从外部原型继承作用域的指令,将scope值设置为true,简单来说就是实现可隔离的继承,即子作用域不能影响父作用域。



作者:MakingChoice
链接:https://www.jianshu.com/p/50d78a1459ac


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP