javascript - angularjs 中數組的修改問題
問題描述
最近在使用 angularjs 遇到一個修改數組的問題。HTML 代碼如下
<span>title1</span><span>title2</span>
js 代碼如下
$scope.title1 = '標題1'$scope.title2 = '標題2'$scope.arrTitle = [$scope.title1, $scope.title2];//我試著修改 $scope.arrTitle[0] = 'xx';
但是 $scope.title1 沒有修改?$scope.arrTitle[0] 打印過出來應該就是 $scope.title1 的啊?請問大神們指點一下,應該怎么修改才行?謝謝。
問題解答
回答1:$scope.arrTitle已經是一個新的變量了(數組)
你修改$scope.arrTitle[0],只是修改其第一個元素的數據。
$scope.arrTitle = [$scope.title1, $scope.title2];只是給數組賦初始值而已。
你希望改變$scope.arrTitle[0]時,$scope.title1也改變,那就用$scope.$watch吧
回答2:其實可以把arrTitle聲明為一個對象
<span ng-bind='arrTitle.title1'></span><span ng-bind='arrTitle.title2'></span>
$scope.arrTitle = { title1: '標題1', title2: '標題2'};//修改 $scope.arrTitle.title1 = 'xx';
相關文章:
1. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””2. docker-machine添加一個已有的docker主機問題3. css - 求推薦適用于vue2的框架 像bootstrap這種類型的4. Span標簽5. angular.js使用$resource服務把數據存入mongodb的問題。6. SessionNotFoundException:會話ID為null。調用quit()后使用WebDriver嗎?(硒)7. android新手一枚,android使用httclient獲取服務器端數據失敗,但是用java工程運行就可以成功獲取。8. css - 關于div自適應問題,大家看圖吧,說不清9. redis啟動有問題?10. java - Collections類里的swap函數,源碼為什么要新定義一個final的List型變量l指向傳入的list?
