0

I'm trying to write a simple directive for a dropdown populated from a service:

    <select class="form-control"
        name="model"
        id="modelInput"
        ng-model="campaign.model"
        ng-change="changed()">
        <option>
            "--select model--"
        </option>    
        <option ng-repeat="existingModel in allModels" value="{{existingModel}}">
            {{existingModel}}
        </option>
    </select>
(function () {
    'use strict';

    var module = angular.module('components.widgets', ['rest.services']);

    module.directive('modelNameSelector', function ($http, $rootScope, modelNames) {
        return {
            restrict: 'E',
            templateUrl: 'app/components/model/model-name-selector.html',

            controller: function ($scope, modelNames) {
                var t = 'thing'
                modelNames.getAll().$promise.then(function(data){
                    //why can't I see 't'???
                    //why can't I access $scope?
                });
                $scope.changed = function(){
                    //I can't see it here too
                }
            }
        }
    });

})();

modelNames.getAll() talks to a resource, and comes back with the right data, but I need to do some stuff when it comes back and I can't access scope or anything defined outside the callback closure. Inside the changed callback, I can access the scope with this, but inside the callback from getAll, this is the window. I'm really confused.

Nikos Paraskevopoulos
  • 39,514
  • 12
  • 85
  • 90
JSFrank
  • 13
  • 2
  • If you hit break-point you will not be able to, but add code that access `t` and `$scope` and the variables will be available. – Chandermani Jan 05 '15 at 15:48
  • 1
    You're right. That's had me stumped for AGES! Thanks very much! Why does that happen? Why can't the breakpoint see the variables? – JSFrank Jan 05 '15 at 15:49
  • This is an optimization, I think from the JS engine. See e.g. [this post](http://stackoverflow.com/questions/26776876/chrome-debugger-unused-variables-not-loaded-in-a-javascript-closure). – Nikos Paraskevopoulos Jan 05 '15 at 16:01

0 Answers0