" ". , .
:
<div ng-component="test.controller({$stateParams: { id: 1}})" template="test.html"></div>
<div ng-component="test.controller({$stateParams: { id: 2}})">
<div>Transcluded Template ID: {{id}}</div>
</div>
:
.directive('ngComponent', function($compile, $parse, $controller, $http, $templateCache) {
return {
restrict: 'A',
transclude: true,
scope: true,
compile: function(tElement, tAttr) {
return function(scope, element, attrs, ctrl, transclude) {
var parseControllerRef = function(ref, current) {
var preparsed = ref.match(/^\s*({[^}]*})\s*$/),
parsed;
if (preparsed) ref = current + '(' + preparsed[1] + ')';
parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
if (!parsed || parsed.length !== 4) throw new Error("Invalid component ref '" + ref + "'");
return {
controller: parsed[1],
paramExpr: parsed[3] || null
};
};
var ref = parseControllerRef(attrs.ngComponent);
scope.$eval(ref.paramExpr);
if(attrs.template) {
$http.get(attrs.template, {cache: $templateCache}).then(function(result){
var template = $compile(result.data)(scope);
element.append(template);
},
function(err){
});
}
else {
transclude(scope, function(clone) {
element.append(clone);
})
}
var locals = {
$scope: scope
}
angular.extend(locals, scope.$parent.$eval(ref.paramExpr));
var controller = $controller(ref.controller, locals);
element.data("ngControllerController", controller);
};
}
};
})
.controller('test.controller', function($scope, $stateParams) {
$scope.id = $stateParams.id;
})
, uiSref ( , angular API).
ngComponent is a kind of “lightweight” directive that can be declared in your markup without actually building the directive. You could probably take it a little further, but at some point you cross the line to write a directive anyway.
source
share