AngularJS:在 element.append 中添加 ng-click

标签 angularjs directive

在我的指令中,我有以下代码,这些代码将用于不断附加到 html 元素。

//Establishes the type of question and therefore what should be displayed
app.directive('questionType', function ($http, $compile) {
    return {
        restrict: 'A',    
        link: function (scope, element, attr, model) {

            switch (scope.Question.inputType) {
                case 'checkbox':
                    //element.append('<input type="checkbox" ng-model="Question.checked"/><button ng-if="input.checked" >X</button>');
                    break;
                case 'text':
                    element.append('<button class="btn btn-info" ng-click="selectProperties()" title="Assign this user"><span class="glyphicon glyphicon-user"></span>Assignment</button>');
                    break;
            }
        }
    };
});

因此,当我单击按钮时,应该调用 selectproperties 函数,该函数位于要附加的元素周围的 Controller 内。但是它没有被调用,而且我知道该函数可以正常工作,因为如果我将此按钮代码直接放入 html 页面中,它就会正常工作。

我已经看到使用 $compile 是解决这个问题的一种方法,但是当我使用它时它只会导致我的网页卡住,并且控制台中不会出现任何错误。

我尝试了其他几种方法,例如将带有该方法的 Controller 添加到我的指令中 -

    controller: function ($scope, $element) {
        $scope.selectProperties = function () {
            aler('test');
        }
    }

但这也没有用。而且我需要能够使用函数调用来更新我的主 Controller 中的对象,所以我不确定我是否可以那样做。

有什么想法吗?

最佳答案

您应该编译 html 以将指令(如ng-click)绑定(bind)到作用域属性。其他副 Angular 指令不会绑定(bind)到范围属性。

var strElm = '<button class="btn btn-info" ng-click="selectProperties()" title="Assign this user"><span class="glyphicon glyphicon-user"></span>Assignment</button>';
var compiledHtml = $compile(strElm);
element.append(compiledHtml);

并且不要从指令中删除$compile服务,

你的代码应该是这样的,

//Establishes the type of question and therefore what should be displayed
app.directive('questionType', function($http, $compile) {
  return {
    restrict: 'A',
    link: function(scope, element, attr, model) {

      switch (scope.Question.inputType) {
        case 'checkbox':
          //element.append('<input type="checkbox" ng-model="Question.checked"/><button ng-if="input.checked" >X</button>');
          break;
        case 'text':
          var strElm = '<button class="btn btn-info" ng-click="selectProperties()" title="Assign this user"><span class="glyphicon glyphicon-user"></span>Assignment</button>';
          var compiledHtml = $compile(strElm);
          element.append(compiledHtml);
          break;
      }
    }
  };
});

关于AngularJS:在 element.append 中添加 ng-click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51171323/

相关文章:

javascript - 为什么我的 Angular 方法没有从信号器接收到任何内容

jquery - 在 tomcat 上运行 spring 应用程序时更新我的​​ html/css/js 文件的方法

javascript - 仅当外部更改时才触发 $watch

angularjs - 根据 $scope 值在 View 中加载 Angular 指令

javascript - 如何从主 Controller 发出数据以 Angular 查看 Controller ?

javascript - 基于 ng-class 改变背景颜色

JavaScript 指令没有像我想象的那样工作

angularjs - 如何在不更改标记的情况下仅使用相同指令定位某些元素?

angularjs - 如何使用已编译元素在单元测试中访问 c​​ontrollerAs 命名空间?

javascript - 使用动态模板编写 Angular Directive(指令)测试