서비스에 저장된 배열에 범위 바인딩이 있습니다. 배열이 변경되면 범위가 변경 사항을 인식하고 내 템플릿의 값을 업데이트합니다.배열이 교체 될 때 서비스 배열에 대한 내 범위 바인딩이 업데이트되지 않는 이유
그러나 배열이 다른 배열로 대체되면 범위가 변경 사항을 인식하지 못하는 것으로 나타나서 목록을 업데이트하지 않습니다.
나는 이것이 angularjs의 공통적 인 행동이며 이것이 아마 이런 경향이 있음을 알고 있습니다. 그러나 저는 왜 그런지 알지 못합니다. 바운드 참조가 변경 될 때마다 범위 변수가 업데이트되어야합니다.
$scope.myVar = anyOtherVar;
은 $scope.$watch('anyOtherVar',function(..){//update myVar});
과 같지 않습니까?
문제를 설명하기 위해 내 피들을 참조하십시오. http://jsfiddle.net/sL9k7q9L/1/
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
myApp.factory('myService', function() {
var anyArray = [{"name":"peter"}];
var anyOtherArray = [{"name":"laura"}];
return {
anyArray: anyArray,
newElement: function(){
anyArray.push({"name":"bob"});
},
replaceWholeArray: function(){
anyArray = anyOtherArray;
console.log(anyArray);
}
}
});
function MyCtrl($scope,myService) {
$scope.elements = myService.anyArray;
$scope.newElement = function(){
myService.newElement();
}
$scope.replaceWholeArray = function(){
myService.replaceWholeArray();
}
}
하고 해당 템플릿 :
<div ng-controller="MyCtrl">
<button ng-click="newElement()">
newElement()
</button>
<button ng-click="replaceWholeArray()">
replaceWholeArray()
</button>
<ul>
<li ng-repeat="el in elements">{{el.name}}</li>
</ul>
</div>
모든 관련 코드는 질문 자체에 포함되어야합니다. 질문 자체가 포함되어야합니다. 데모는 사실 – charlietfl