2017-08-16 30 views
1

所有我想要的是開模 之前設置一個範圍change所以我把ng-click="change = false;mode = 'edit';"的編輯按鈕AngularJS不會設置範圍變量,NG-點擊

錯誤的情況是,當我點擊編輯範圍應該是false ,但如果我通過按更改按鈕將其更改爲true,然後關閉模式,然後再次單擊編輯以再次打開模式,您可以看到範圍仍然爲真,而應該重置爲假

任何解釋?

我在Plunker由本例,

下面的代碼:

<!DOCTYPE html> 
 
<html ng-app="app"> 
 

 
<head> 
 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> 
 
    <script> 
 
    var app = angular.module('app', []); 
 
    app.controller('MainCtrl', function($scope) { 
 
    }); 
 
    </script> 
 
</head> 
 

 
<body ng-controller="MainCtrl"> 
 
    <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" ng-click="mode = 'add'">Add</button> 
 
    <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" ng-click="change = false;mode = 'edit';">Edit</button> 
 
    <!-- Modal --> 
 
    <div class="modal fade" id="myModal" role="dialog" ng-switch on="mode"> 
 
    <div class="modal-dialog"> 
 

 
     <!-- Modal content--> 
 
     <div class="modal-content"> 
 
     <div class="modal-header"> 
 
      <button type="button" class="close" data-dismiss="modal">&times;</button> 
 
      <h4 class="modal-title" ng-switch-when="add">Add</h4> 
 
      <h4 class="modal-title" ng-switch-when="edit">Edit</h4> 
 
     </div> 
 
     <div class="modal-body"> 
 
      <p>{{mode}} </p> 
 
      <button type="button" class="btn btn-default" ng-click="change = false" ng-show="change">Change</button> 
 
      <button type="button" class="btn btn-default" ng-click="change = true" ng-show="!change">Revert</button> 
 
      <p>{{change}} </p> 
 
     </div> 
 
     <div class="modal-footer"> 
 
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
 
     </div> 
 
     </div> 
 

 
    </div> 
 
    </div> 
 
</body> 
 

 
</html>

回答

1

這是因爲角使用原型繼承同時創造非隔離範圍。由於ng-repeat/ng-if/ng-if這些模板指令創建原型繼承的子作用域,同時在其中渲染橫向排列的DOM。值得一讀What are the nuances of scope prototypal/prototypical inheritance in AngularJS?。這種問題通常發生在原始數據類型中,如string,bool,number等。解決此問題的一般實踐將使用object(引用類型)。在定義角度範圍上的模型時使用引用類型,稱爲Dot Rule

在你的場景中,你可以考慮創建$scope.model = {}對象,它最終會保存你所有與該實體相關的屬性。在HTML上使用它們時使用model.change & model.edit

甚至可以在定義控制器時使用controllerAs語法,它將所有綁定變量綁定到this(上下文)而不是$scope

Demo Plunker

+0

感謝您的解釋和工作演示!我有很多要了解AngularJS –

+0

@SoltaniNeji很高興幫助你,謝謝:) –

+0

肯定它幫了很多 –