zoukankan      html  css  js  c++  java
  • angularjs中的绑定策略“@”,“=”,“&”实例

    <!DOCTYPE html>
    <html lang="zh-CN" ng-app="app">
    <head>
        <meta charset="utf-8">
        <title>绑定策略</title>
        <link rel="stylesheet" href="../bootstrap.min.css">
    </head>
    <body>
        <h4>
            AngularJS提供了几种方法能够将指令内部的隔离作用域,同指令外部的作用域进行数据绑定。
        </h4>
        为了让新的指令作用域可以访问当前本地作用域中的变量,需要使用下面三种别名中的一种(以下为官方的解释):
        <ol>
            <!--本地作用域属性:使用@符号将本地作用域同DOM属性的值进行绑定。指令内部作用域可以使用外部作用域的变量。-->
            <li>@ (or @attr)</li>
            <!--双向绑定:通过=可以将本地作用域上的属性同父级作用域上的属性进行双向的数据绑定。 就像普通的数据绑定一样,本地属性会反映出父数据模型中所发生的改变。 -->
            <li>= (or =attr)</li>
            <!--父级作用域绑定 通过&符号可以对父级作用域进行绑定,以便在其中运行函数。意味着对这个值进行设置时会生成一个指向父级作用域的包装函数。 
            要使调用带有一个参数的父方法,我们需要传递一个对象,这个对象的键是参数的名称,值 是要传递给参数的内容。-->
            <li>& (or &attr)</li>
        </ol>
    
        <div style="border: 1px solid red; 400px;height: 200px;" ng-controller="ParentController">
            <p style="color: orange;">请认真记住以下输入框中的提示文字</p>
            记住了?<input type="checkbox" ng-model="isRemember">
            <p ng-show="isRemember">
                <input type="text" ng-model="someVal" placeholder="随意输入几个值">
                并试着改变下面两个input的值
            </p>
            <div ng-show="!isRemember || someVal" my-directive one-val="{{someVal}}" two-val="someVal" three-val="parentFun('哈哈')"></div>
        </div>
        
        <script src="../angular.min.js"></script>
        <script>
            angular.module('app', [])
            .directive('myDirective', function() {
                return {
                    restrict: 'A', 
                    replace: true,
                    scope: {
                        oneVal: '@oneVal', // 相当于“值复制”
                        twoVal: '=twoVal', // 相当于“引用复制”
                        threeVal: '&threeVal' // 绑定父作用域中的方法
                    },
                    template: '<div>'+
                                '<input type="text" ng-model="oneVal" placeholder="@ 改变我其他不受影响">'+
                                '<input type="text" ng-model="twoVal" placeholder="= 要是动我其他都得变">'+
                                '<input type="button" ng-click="threeVal()" value="$ 点我试试">'+
                              '</div>'
                                
                    
                }
            })
            .controller('ParentController', function($scope) {
                $scope.parentFun = function(s) {
                    alert("我成功绑定了父级作用域中的函数!" + s);
                }
            })
        </script>
    </body>
    </html>

    以上实例可以直接运行,动手跑跑更有意思哦!

  • 相关阅读:
    四种wordpress常用的循环结构
    自动创建网页文章目录结构
    shell
    SSH
    架构
    Https
    if-else、switch、while、for
    do-while
    const
    Tail Call
  • 原文地址:https://www.cnblogs.com/BGOnline/p/5985374.html
Copyright © 2011-2022 走看看