You might want to refer to the Angular documentation for directives, again.
If you want an isolate-scope (a scope which has no access to ancestors), then use
scope : { /* ... */ }
otherwise, if you want a unique scope, which does have access to ancestors, use
scope : true
Then, you can put your HTML-modifying or event-listening (that doesn't rely on ng-click or something else Angular already covers) in
link : function (scope, el, attrs, controller) { }
...and you can put all of your regular implementation inside of
controller : ["$scope", function ($scope) {
var myController = this;
myController.property = "12";
}],
controllerAs : "myController"
So that in your template you can say:
<span>{{ myController.property }}</span>
You can also use a pre-registered controller, which you call by name:
controller : "mySimpleController",
controllerAs : "myController"
Also, rather than using $scope.$apply
, I'd recommend using $timeout
(has to be injected).
The difference is that $scope.$apply
will only work at certain points -- if you're already inside of a digest cycle, it will throw an error, and not update anything.
$timeout( )
sets the updates to happen during the next update-cycle.
Ideally, you should know whether or not you need an $apply
or not, and be able to guarantee that you're only using it in one spot, per update/digest, but $timeout
will save you from those points where you aren't necessarily sure.