问题
I have the following directive:
offerListSorters.directive('offersSorter', ['myState', '$templateCache', function (myState, $templateCache){
return {
scope: {},
controller: function($scope, $element, $attrs, $transclude) {
[...]
},
restrict: 'E',
//templateUrl: 'partials/offersSorterDirective.html',
template: $templateCache.get('partials/offersSorterDirective.html'),
replace: true,
transclude: true
};
}]);
And I use Karma + Jasmine to test this code and it works. But now if I switch to the templateUrl (currently commented out), it doesn't work. I've created a simple Plunker to show this issue. When you compare sorter and bsorter directives, it looks as if the isolateScope() call on the compiled element breaks when I use templateUrl instead of template. Any ideas?
回答1:
It's the weirdest thing, I think this is actually a bug where if you're using a templateUrl, you don't get an isolated scope. The template itself is loaded correctly, but the scope is never loaded. I've updated the plnkr with some additional logging, checkout out the console and you'll see what I mean, bsorter
doesn't get the ng-isolate-scope class and the scope is returned as undefined.
Edit:
I've updated the plnkr further to log a console message when the compile function is called. This is pretty much the limit of my javascript/angularJS knowledge, but the bsorter compile function is logged as being called after the scope should be returned, unlike the sorter compile function which is called before.
回答2:
You should call isolateScope() in the it() function, not in beforeEach().
describe("Testing...", function(){
var element, isoScope;
beforeEach(function(){
module("myApp");
inject(function($rootScope, $compile){
var scope = $rootScope.$new();
element = $compile(angular.element("<sorter></sorter>"))(scope);
// isoScope = element.isolateScope(); <- Move from here
$rootScope.$digest();
});
});
it("something...", function(){
isoScope = element.isolateScope(); // <- to here
expect(isoScope.someProp).toBe("someValue");
});
});
回答3:
You have to call $rootScope.$digest() after creating the directive via $compile, then it should work (right now you're calling the $digest() on the on your variable parentScope with is a new scope created with $rootScope.$new())
来源:https://stackoverflow.com/questions/23023269/angularjs-templateurl-vs-template-isolate-scope