[英]custom angularjs directive with scope and ng-controller
I want to create directive that has scope parameters and ng-controler both. 我想创建同时具有范围参数和ng-controler的指令。
This is how this directive should look: 这是该指令的外观:
<csm-dir name="scopeParam" ng-controller="RegisteredController">
<!--Here I want to have content-->
{{name}}
</csm-dir>
I have "RegistertedController" declared somewhere in my app. 我在我的应用中的某个地方声明了“ RegisteredController”。
angular.module('app')
.controller('RegisteredController', ['$scope', function ($scope) {
//$scope.name should be accessible here
}]);
And I am trying to declare directive: 我正在尝试声明指令:
angular.module('app')
.directive('csmDir', [function () {
return {
restrict: 'AE',
replace: true,
transclude: true,
scope: {
name: '='
},
template: '<section class="layout"><ng-transclude></ng-transclude></section>',
link: function (scope, element, attr, ctrl, transclude) {
element.find('ng-transclude').replaceWith(transclude());
//here I also need scope.name parameter
}
};
});
I get error: 我得到错误:
Multiple directives [ngController, csmDir] asking for new/isolated scope on: <csm-dir name="scopeParam" ng-controller="RegisteredController">
Now this error is quite informative, and I get it angular doesn't work as I would like here. 现在,此错误非常有用,我知道它在角度上不起作用,就像我在这里想要的那样。
I could remove "scope: {..}" parameter from directive and define it in controller, but it's not what I need. 我可以从指令中删除“ scope:{..}”参数并在控制器中定义它,但这不是我所需要的。
What I need is basically to provide ng-controller to custom directive, and then provide additional scope variables for that controller. 我基本上需要为ng-controller提供自定义指令,然后为该控制器提供其他范围变量。
How can I achieve this? 我该如何实现?
You have to wrap your directive with tag and put controller there. 您必须使用标记包装指令并将控制器放在此处。
<div ng-controller="RegisteredController">
<csm-dir name="scopeParam">
<!--Here I want to have content-->
{{name}}
</csm-dir>
</div>
There is no way to get two isolated scopes in one tag. 无法在一个标签中获得两个隔离的作用域。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.