Angular 从自己的范围指令调用函数
Angular Directive Call function from own scope
我正在构建一个显示项目列表的 Angular
指令。项目列表由该指令自己的函数 scope
提供。下面是我正在做的事情的基本版本(listOpts
需要是一个 fn 而不是静态数据)。编译模板时 listOpts
未被评估,因此模板 returns 为空 ul
。当我将 listOpts
fn 放在父 controller
中时,它会对其进行评估。但是因为SRP(单一职责原则),我不想把listOpts
函数放在controller中; listOpts
函数 属于 list
指令而不是 controller
。我一定是对指令的工作方式或模板的编译时间有误解?我应该用指令将 listOpts
fn 放在 controller
fn 中吗?
@app.directive "list", () ->
restrict: "E"
link: (scope, el, attrs, ctrl) ->
scope.listOpts = ()->
return [1,2,3]
template: "
<ul ng-repeat='item in listOpts()'>
<li>{{item}}</li>
<ul>
"
提供的示例代码似乎按原样工作:
http://plnkr.co/edit/r589eFGZm8MOTk94GJtk?p=preview
刚刚修改为使用常规 JS,这里到底有什么问题,你能在 plnkr 中重现问题吗?
.directive("list", function() {
return {
restrict: "E",
link: function(scope, el, attrs, ctrl){ scope.listOpts = function(){return [1,2,3];}},
template: "<ul ng-repeat='item in listOpts()'><li>{{item}}</li><ul>"
}
})
我正在构建一个显示项目列表的 Angular
指令。项目列表由该指令自己的函数 scope
提供。下面是我正在做的事情的基本版本(listOpts
需要是一个 fn 而不是静态数据)。编译模板时 listOpts
未被评估,因此模板 returns 为空 ul
。当我将 listOpts
fn 放在父 controller
中时,它会对其进行评估。但是因为SRP(单一职责原则),我不想把listOpts
函数放在controller中; listOpts
函数 属于 list
指令而不是 controller
。我一定是对指令的工作方式或模板的编译时间有误解?我应该用指令将 listOpts
fn 放在 controller
fn 中吗?
@app.directive "list", () ->
restrict: "E"
link: (scope, el, attrs, ctrl) ->
scope.listOpts = ()->
return [1,2,3]
template: "
<ul ng-repeat='item in listOpts()'>
<li>{{item}}</li>
<ul>
"
提供的示例代码似乎按原样工作:
http://plnkr.co/edit/r589eFGZm8MOTk94GJtk?p=preview
刚刚修改为使用常规 JS,这里到底有什么问题,你能在 plnkr 中重现问题吗?
.directive("list", function() {
return {
restrict: "E",
link: function(scope, el, attrs, ctrl){ scope.listOpts = function(){return [1,2,3];}},
template: "<ul ng-repeat='item in listOpts()'><li>{{item}}</li><ul>"
}
})