這篇文章主要介紹了淺談angularJS 作用域的相關資料,需要的朋友可以參考下
- <!doctype html>
- <html ng-app="firstApp">
- <head>
- <meta charset="utf-8">
- <script src="angular-1.3.0.js"></script>
- </head>
- <body>
- <div ng-controller="parentCtrl">
- <input ng-model="args">
- <div ng-controller="childCtrl">
- <input ng-model="args">
- </div>
- </div>
- <script>
- var app=angular.module('firstApp',[]);
- app.controller('parentCtrl',function($scope) {
- $scope.args = '123';
- }).controller('childCtrl', function($scope) {
- });
- </script>
案例說明:
雖然在 childCtrl 中沒有定義具體的 args 屬性,但是因為 childCtrl 的作用域繼承自 parentCtrl 的作用域,
因此,childCtrl通過原型鏈 到父作用域args 屬性并設置到input中。且在父input中輸入值自己動同步到子input中
但是反之不行。即子中修改,無法改變父中的值,且導致父修改后子也不同步了,原因:在子作用域input輸入內容時,
因為 HTML 代碼中 model 明確綁定在 childCtrl 的作用域中,因此 AngularJS 會為 childCtrl 生成一個 args 原始類型屬性。
根據 AngularJS 作用域繼承原型機制,childCtrl 在自己的作用域找到args屬性值,故就不從父中查找args值。
導致最終子作用域有args,父作用域有args,子和父之間的值不會再保持同步。
以上所述就是本文的全部內容了,希望大家能夠喜歡。
新聞熱點
疑難解答
圖片精選