Question

There are two ways (or there is smth else?) to use function in templates:

1. Declare it in $rootScope:

app.run(function ($rootScope) {
  $rootScope.makeURL = function (url) { 
    return 'http://mysite.ru/' + url;
  }
});

and in Templates:

<a href="makeURL('blog')">go Blog</a>

2. Declate it like Directive:

app.directive('makeURL', function () {
  return {
     link: function ($scope, $element, $attrs) {
        var url = 'http://mysite.ru/' + $attrs.makeurl; // just example

        $element.attr('href', url);
     }
  }
} 

and in Templates:

<div ng-controller="SomeCtrl">
  <a makeURL="blog">go Blog</a>
</div>

Or mbe i need to use Filter ? What is the best way? And can I use $rootScope for such things? or its the worst way? and why? Plz I need to understand these things.


EDITED: I think this is the answer: Angular JS - Make service globally accessible from controllers and view

Était-ce utile?

La solution

Use a service

mymodule.service('URL',function(){
 this.make=function(){...}
});

mymodule.controller($scope,URL){
$scope.URL=URL;
}

<a href="{{Url.make(somedata)}}"/>

A service will make you controller more testable AND you'll be able to test the service in isolation. It's more difficult if you add anything to the rootscope in the angular.run method.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top