【问题标题】:Angular. call function in directive from html角。从 html 指令中调用函数
【发布时间】:2015-11-18 20:19:23
【问题描述】:

我正在尝试制定指令。这样我就可以在我的 html 页面中使用它,如下面的 sn-p:

<testview></testview>

现在唯一要做的就是渲染一个类似的链接

<a><span ng-onmousedown='onSelected(\"creame\",event)'>{{value}}</span></a>

当我单击跨度时,我希望指令通过调用 onSelected 函数来更改 $scope.value。但我不能这样称呼。

完整代码示例

function testView() {

    $scope.value =
    {
        name: "dummy"
    }

    testHtml += "<a><span ng-onmousedown='onSelected(\"creame\",event)'  >" + $scope.value.name + "</span></a>";
    return {
        restrict: 'AE',
        replace: 'true',
        template: testHtml,
    };
}
app.directive('testview', testView);

function onSelected(input)
{
    $scope.value.name = input;
}

有人知道我该怎么做吗? 感谢您的宝贵时间

【问题讨论】:

  • "但我不能这样称呼。" 为什么不呢?如果你像任何其他常规函数一样调用它会发生什么?
  • 你必须将函数添加到 $scope
  • @takendarkk 没有,没有错误。
  • 我认为是 ng-mousedown

标签: javascript html angularjs angularjs-directive angularjs-scope


【解决方案1】:

试试这个

function testView() {

testHtml += "<a><span ng-onmousedown='onSelected(\"creame\")'  >{{value.name }}</span></a>";
    return {
        restrict: 'AE',
        replace: 'true',
        template: testHtml,
    };
}
app.directive('testview', testView);
app.controller('CampaignsOverviewController', Controller);

function Controller ($scope) {
  $scope.onSelected = onSelected;
  $scope.value =
       {
          name: "dummy"
       }
     function onSelected(input)
       {
         $scope.value.name = input;
        }

 }

【讨论】:

  • 我试图将函数保留在指令中
  • 在指令对象中,添加属性controller 并分配一个具有您为控制器名称指定的值的字符串。急用CampaignsOverviewController,换个更有用的吧
  • 你必须提供一个控制器来绑定这些方法
【解决方案2】:

我认为您需要先compile 您的模板才能执行 ngOnMouseDown 指令。

【讨论】:

    猜你喜欢
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 2015-04-21
    相关资源
    最近更新 更多