2017-01-04 25 views
0

重复按下按钮一个div我在这里以下的教程:https://fourtonfish.com/blog/2014-01-dynamically-add-directives-in-angularjs-no-jquery/在AngularJS

尝试,当按下一个按钮附加信息核实。我有添加到我的主页按钮,但是当我点击它,我得到:

angular.js:14324 TypeError: element.bind is not a function 

我很想如何纠正一些这方面的建议,甚至可能是一个更好的办法,如果有一个。我觉得使用element.bind是一个jQuery的方法,可能有更好的方法来做到这一点与Angular?

main.html中

<div id ="fullForm" ng-controller="MainCtrl" >     
    <button-add></button-add> 
    <div id="test">test</div> 
</div> 

main.js

'use strict'; 

/** 
* @ngdoc function 
* @name jsongeneratorApp.controller:MainCtrl 
* @description 
* # MainCtrl 
* Controller of the jsongeneratorApp 
*/ 
angular.module('jsongeneratorApp') 
    .controller('MainCtrl', function ($scope) { 

    .directive('buttonAdd',function(){ 
    return{ 
    restrict:'E', 
    templateUrl:'scripts/directives/addbutton.html' 
    } 
}) 

.directive('addfields',function($compile){ 
    console.log("directive called."); 
    return function(element,attrs){ 
    element.bind("click",function(){ 
     angular.element(document.getElementById('test')).append($compile("<div>Test</div>")) 
    }) 
    } 
}) 

addbutton.html

<div class="row rowmargin"> 
    <div class="col-sm-9"> 
    </div> 
    <div class="col-sm-3"> 
    <button addfields class="btn"> Add New Variable</button> 

    </div> 
</div> 
+0

本教程可能使用较老版本的angular。而不是'element.bind'使用'element.on'。请参阅[本文档](https://docs.angularjs.org/api/ng/function/angular.element),您可以看到'bind'已弃用 – devqon

+0

element.on(“click”,function().. 。产生相同的错误 –

回答

1

元件是第二个参数,而不是第一个。第一个是指令的$scope对象。

您可能有可能与angular的依赖注入混淆,但指令的link函数不适用于依赖注入。

如果您在签名中添加范围参数,将工作:

// You missed the first parameter 'scope' 
return function(scope, element, attrs){ 
    element.on("click",function(){ 
     $compile("<div>Test</div>")(scope, function(compiled){ 
      // callback 
      angular.element(document.getElementById('test')).append(compiled); 
     }); 
    }); 
} 

也请注意,bind功能is deprecated,所以你应该使用on代替。

+0

感谢您的建议。添加范围导致错误: 未捕获的错误:[ng:areq]参数'范围'是必需的,我觉得有点混淆你也知道范围需要是添加了吗?有没有办法让我检查函数,还是只带有经验? –

+0

是的,这是因为'$ compile'服务期望一个作用域来编译html:'$ compile(“

Test
”)(作用域) ' – devqon

+0

所以这个工作现在..非常感谢你!但是我有点困惑你怎么知道它需要的范围,我也从来没有见过(范围)语法添加到函数的结尾之前。解释一下? –