Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

controller - How can I call a service from a template in AngularJS?

I have a service that returns a json object that it makes, for brevity lets say it looks like this:

.service ('levelService', function () {

    // service to manage levels.
    return  {
        levels : [{name:'Base', href:'base'},{name:'Level 1', href:'level1'},{name:'level2', href:'level2'}]
    };

})

I think that is fine, but I want to use it now, in a template. Currently I have something like this:

<ul class="dropdown-menu" ng-init="levels = [{name:'Base', href:'base'},{name:'Level 1', href:'level1'},{name:'level2', href:'level2'}];">
                      <li ng-repeat="level in levels">
      <a ng-href="#/modeling/level/{{level.href}}">{{level.name}}</a></li>
                  </ul>

How can I get the ng-init to now use the service? I feel like the right thing to do, is add the service to the controller, but this is outside of any controller. Do i need to create a new controller for this space, or can i directly reference the service?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, it would be best practice to create a controller.

The idea behind the MVC app architecture is that you don't tightly couple your objects/classes together. Injecting a service into a controller, then subsequently your controller adding levels to $scope means that your HTML doesn't have to worry about where it gets the data from.

Also, using ng-init in that way is arguably fine for knocking up a very quick prototype, but that approach shouldn't be used in production code (as your model's data itself is tightly coupled to your view's HTML).

Tip: It might be a good idea to use a controller for the parent container of your dropdown-menu (ie. the page/section) and then use a directive for your dropdown-menu itself. Think of a directive as a view component.

In general, you might find the video tutorials at egghead.io helpful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...