-2

All the documentation I can find talks about the view automatically updating the model. However, using the example controller:

var phonecatApp = angular.module('phonecatApp', []);

phonecatApp.controller('PhoneListCtrl', function ($scope) {
  $scope.phones = [
    {'name': 'Nexus S',
     'snippet': 'Fast just got faster with Nexus S.',
     'age': 1},
    {'name': 'Motorola XOOM™ with Wi-Fi',
     'snippet': 'The Next, Next Generation tablet.',
     'age': 2},
    {'name': 'MOTOROLA XOOM™',
     'snippet': 'The Next, Next Generation tablet.',
     'age': 3}
  ];

  $scope.orderProp = 'age';
});

Within JavaScript, how would I (for example) change phones to an empty array? Basically I would like to do

$scope.phones = [];

(and have the view update automatically) but I can't figure out how to 'get to' the phones variable

Hoa
  • 19,858
  • 28
  • 78
  • 107

1 Answers1

2

If you're just trying to empty the array, then inside of that controller add a function to clear the array. Then use a directive to call the function. Example:

JS:

$scope.clearPhoneData = function() {
    $scope.phones.length = 0;
};

HTML:

<div ng-click="clearPhoneData()">Clear</div>

If you're trying to access the data from outside of this controller, then what you really want to do is set up a service that retrieves the phone data and makes it available to controllers that use the service. Then your controller uses the service as a dependency and you do something like:

$scope.$watch(function() {
    return phoneService.phones;
}, function(newData) {
    $scope.phones = newData;
});

It's really unclear what you want, but I implore you not to use $scope.$apply() when it's unnecessary.

Here is a plunkr that should help you: http://plnkr.co/edit/LwvZCz941CX9BGMqRhXe?p=preview

It shows the implementation of a service and how you can use it to access data across multiple controllers, clear the data, etc.

Shelby L Morris
  • 726
  • 5
  • 10