angularjsangularjs-directiveangularjs-scopeangularjs-resource

Updating $scope in an Angular directive


I m using the following, after much frustration and Googling I cannot get the data_banks item to update in the $scope after the $resource for Marketplace.buy has been loaded successfully;

myApp.directive('marketplaceBuy', function() {
    return {
        restrict: 'A',
        controller: ['$scope', "$timeout", "Marketplace", "Notification", "DataBank", function ($scope, $timeout, Marketplace, Notification, DataBank) {
            $scope.dooo = function(attrs) {
                Marketplace.buy({'item': attrs.itemId},
                    function(){
                        DataBank.query({word: "databanks"}, function(data){
                            $scope.data_bank = data.data;
                        });
                    }, function(resp){
                        Notification.error(resp.data.message);
                    });
            }
        }],
        link: function ($scope, element, attrs) {
            element.bind('click', function () {
                $scope.dooo(attrs);
            });
        }
    };
});

Using $scope.$apply() errors.

EDIT

The original data_bank is loaded like so

myControllers.controller('LocationListCtrl', ['$scope', 'DataBank', function($scope, DataBank) {
    $scope.data_bank = DataBank.query({word: "databanks"});
});

And it is bound to a view like so

<body ng-cloak>
    <div ng-view>
         <div ng-repeat="blue_print in data_bank.blue_prints">{{ blue_print.name }}</div>
     </div>
</body>

Finally the controller is loaded like so using a route

myApp.config(['$routeProvider', '$httpProvider',
  function($routeProvider, $httpProvider) {

      $httpProvider.interceptors.push('MyInterceptor');

      $routeProvider.
      when('/locations', {
        templateUrl: "/bundles/app/partials/locations.html",
        controller: 'LocationListCtrl'
      })
  }]);

Solution

  • OK so it turned out I had gotten ahead of myself and wasn't looking at the whole picture. My directive wasn't actually without my ng-view. #lame.

    Because I am using Symfony with its own partials I had not realised that my included partial from Symfony was not inside ng-view , plus ng-view gets replaced anyway by my own Angular templates anyway having the Symfony partial in there wouldn't have worked anyway.

    But after all that I am still having issues with a two-way binding and having my directive write back to all instances of an attribute on $scope so I have abandoned it in favor of a new approach.