![](/img/trans.png)
[英]How to update Vanilla JS variable in scope variable of Angular JS controller
[英]Angular JS how to update scope variable inside another scope variable
我正在使用ng-repeat從對象數組中建立一個列表。 數組中的一個屬性是一個布爾值,它將在ng-show中顯示我正在使用此數組構建的每個元素。 數組本身也是一個作用域變量。
現在,我只想更新顯示屬性。 可能嗎?
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.displayThird = false;
$scope.list = [
{
text: "One",
display: true
},
{
text: "Two",
display: true
},
{
text: "Three",
display: $scope.displayThird
},
{
text: "Four",
display: true
}
];
/* I want this function to update my display property */
$scope.display = function() {
$scope.displayThird = true;
}
});
這是一個常見的誤解:將表達式分配給Javascript中的變量時 ,只會分配表達式的值 。 沒有綁定被創建。 相反,Angular模板中的表達式會創建綁定。
因此,在您的情況下, $scope.list[2].display
分配的值為false
並且不知道如何創建該值。
在Angular中執行此操作的正確方法是使用手表:
$scope.$watch("displayThird", function(newval) {
$scope.list[2].display = newval;
});
這是Angular在使用其模板的基礎上所做的,只有您必須使用Javascript手動進行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.