2

I'm trying to understand dependency injection in AngularJS.

Right now, I'm trying to inject $interpolate and $eval into my controller, but reading the documentation didn't clarify because I don't have a good foundation on Angular.

Take the following code that demonstrates the issue I don't understand:

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

module.controller('ngAppDemoController', function($scope, $parse) {
  $scope.a = 1;
  $scope.b = 2;
  $scope.myHTML = '{{a}}';

});

Can someone help me understand how to inject and $interpolate the myHTML string? Or if interpolation is not correct in evaluating that string, what is? It's a weird case, but I'm just trying to learn right now.

1 Answer 1

1

you're very close. just need to declare it as module dependency and add to function parameters. (i think this should work)

var module = angular.module('ngAppDemo',['$interpolate' ]);

module.controller('ngAppDemoController', function($scope, $parse, $interpolate) {
  $scope.a = 1;
  $scope.b = 2;
  $scope.myHTML = '{{a}}';

});

i've been declaring controllers and injection in this way:

angular.module('app').controller(
        'generator', 
        ['myService', '$http', '$scope', '$interpolate', generator]
);

function generator(myService, $http, $scope, $interpolate) {
    $scope.foo = 'bar';
}

where the controller object (in my case generator) is passed in to the module declaration

Sign up to request clarification or add additional context in comments.

4 Comments

how is $interpolate being injected in the second example?
just like all the other services.. added $interpolate in.
May I edit my question to include how to inject $eval as well? I tried to include $eval in the array and as an argument to the function on JSfiddle, but my program just died: jsfiddle.net/dMp55/1
+1 on @SonicSoul method of setting up a controller - this protects you from Angular minification woes. Side note, do you even have to declare $interpolate as a dependency on the ngAppDemo module? Can't you just pass it to your controller like you're doing on the bottom.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.