zoukankan      html  css  js  c++  java
  • 《AngularJS权威教程》中关于指令双向数据绑定的理解

    在《AngularJS权威教程》中,自定义指令和DOM双向数据绑定有一个在线demo,网址:http://jsbin.com/IteNita/1/edit?html,js,output,具体代码如下:

    <!doctype html>
    <html ng-app="myApp">
    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.js"></script>
    </head>
    <body>
    
      <label>Their URL field:</label>
      <input type="text" ng-model="theirUrl">
      <div my-directive
           some-attr="theirUrl"
           my-link-text="Click me to go to Google"></div>
    
      <script>
        angular.module('myApp', [])
        .directive('myDirective', function() {
          return {
            restrict: 'A',
            replace: true,
            scope: {
              myUrl: '=someAttr',
              myLinkText: '@'
            },
            template: '
              <div>
                <label>My Url Field:</label>
                <input type="text" ng-model="myUrl" />
                <a href="{{myUrl}}">{{myLinkText}}</a>
              </div>
            '
          }
        })
      </script>
    
    </body>
    </html>

    其中myUrl: '=someAttr'我不是很理解,于是改成 myUrl: '@someAttr',但是这样页面显示如图:

    查看元素发现链接的href="theirUrl",并且;两个输入框的内容也不同步,仔细查看代码,发现DOM中将some-attr设置值方式不是表达式,所以修改如下(修改处为绿色):

    <body>
    
      <label>Their URL field:</label>
      <input type="text" ng-model="theirUrl">
      <div my-directive
           some-attr={{theirUrl}}    
           my-link-text="Click me to go to Google"></div>
    
      <script>
        angular.module('myApp', [])
        .directive('myDirective', function() {
          return {
            restrict: 'A',
            replace: true,
            scope: {
              myUrl: '@someAttr',
              myLinkText: '@'
            },
            template: '
              <div>
                <label>My Url Field:</label>
                <input type="text" ng-model="myUrl" />
                <a href="{{myUrl}}">{{myLinkText}}</a>
              </div>
            '
          }
        })
      </script>
    
    </body>

    效果是,第2个输入框随着第1个变化,反之不是。

    总结:指令要访问其内部的指令,需要:

    1.指令属性值用表达式即{{}}设置,改为“”

    2.内部指令对应属性数据绑定”@”改为”=”

  • 相关阅读:
    LeetCode.1(两数之和)
    LeetCode.56(合并区间)
    c++ 数字与字符串的相互转换
    软件工程作业-面向对象方法学
    linux终端下解决you need to be root to perform this command
    vue中 v-bind 与 v-model的区别
    vue的核心:虚拟DOM 和 diff 算法
    弱实体集的必要性、属性随笔
    Ubuntu 18.04下Intel SGX应用程序程序开发——获得OCALL调用的返回值
    Ubuntu 18.04 INTEL SGX 修改案例打印Hello Enclave
  • 原文地址:https://www.cnblogs.com/momoxiaoqing/p/6050348.html
Copyright © 2011-2022 走看看