首页 > 语言 > JavaScript > 正文

浅谈angularJS 作用域

2024-05-06 16:22:43
字体:
来源:转载
供稿:网友

这篇文章主要介绍了浅谈angularJS 作用域的相关资料,需要的朋友可以参考下

 

 
  1. <!doctype html> 
  2. <html ng-app="firstApp"
  3. <head> 
  4. <meta charset="utf-8"
  5. <script src="angular-1.3.0.js"></script> 
  6. </head> 
  7. <body> 
  8.  
  9. <div ng-controller="parentCtrl"
  10. <input ng-model="args"
  11. <div ng-controller="childCtrl"
  12. <input ng-model="args"
  13. </div> 
  14. </div> 
  15. <script> 
  16. var app=angular.module('firstApp',[]); 
  17. app.controller('parentCtrl',function($scope) { 
  18. $scope.args = '123'
  19. }).controller('childCtrl'function($scope) { 
  20.  
  21. }); 
  22. </script> 

案例说明:

虽然在 childCtrl 中没有定义具体的 args 属性,但是因为 childCtrl 的作用域继承自 parentCtrl 的作用域,

因此,childCtrl通过原型链 到父作用域args 属性并设置到input中。且在父input中输入值自己动同步到子input中

但是反之不行。即子中修改,无法改变父中的值,且导致父修改后子也不同步了,原因:在子作用域input输入内容时,

因为 HTML 代码中 model 明确绑定在 childCtrl 的作用域中,因此 AngularJS 会为 childCtrl 生成一个 args 原始类型属性。

根据 AngularJS 作用域继承原型机制,childCtrl 在自己的作用域找到args属性值,故就不从父中查找args值。

导致最终子作用域有args,父作用域有args,子和父之间的值不会再保持同步。

以上所述就是本文的全部内容了,希望大家能够喜欢。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选