AngularJS-如何在指令模板中创建的复选框上单击调用控制器的功能

时间:2014-10-28 06:43:50

标签: javascript jquery angularjs checkbox treeview

我是angularJS的新手。我想使用指令中的模板动态创建复选框。我在单独的文件中创建了控制器和指令。我在模板指令中创建复选框,并希望在复选框的ng-click上调用控制器的功能,但我无法这样做。 这是我的代码示例。

Controller:
var app=angular.module('abc',[]);
app.controller('DemoCtrl', function($scope) {
$scope.ctrlFn = function(test) {
         alert("hi "+test);
          console.log(test);
      }
});

我引用了https://github.com/iVantage/angular-ivh-treeview来创建复选框树视图。我包含了我样本中的所有css和js文件。从链接中我得到了以下js文件,该文件在模板指令中创建复选框,如下所示:

IVH-treeview.min.js:

angular.module("ivh.treeview",[]),
angular.module("ivh.treeview").directive("ivhTreeviewCheckbox",[function(){
    "use strict";
    return{restrict:"A",
        scope:{node:"=ivhTreeviewCheckbox"},
        require:"^ivhTreeview",
        link:function(a,b,c,d){
            var e=a.node,f=d.opts(),g=f.indeterminateAttribute,h=f.selectedAttribute;
            a.isSelected=e[h],
                a.ctrl=d,
                a.$watch(function(){return e[h]},function(b){a.isSelected=b}),
                a.$watch(function(){return e[g]},function(a){b.find("input").prop("indeterminate",a)})},
        template:['<input type="checkbox"','ng-model="isSelected"','ng-change="ctrl.select(node, isSelected)" />'].join("\n")}
}]);

查看:

<div class="col-sm-8" ng-controller="DemoCtrl as demo">
                    <div ivh-treeview="demo.bag"
                         ivh-treeview-selected-attribute="'isSelected'"
                         ivh-treeview-id-attribute="'uuid'"
                         ivh-treeview-expand-to-depth="0">
                     </div>
</div>

我想点击指令模板中创建的复选框来调用ctrlFn()。请建议一种方法来做同样的事。

提前致谢

1 个答案:

答案 0 :(得分:0)

听起来你正在寻找指令和父$ scope之间的双向绑定。

// parent controller scope
$scope.person = { name:'coldstar', class:'sexy beast' };

// directive declaration
<div a-person='person'></div>

// directive code
scope: {
    // the = sign is the key. could also be a function instead of object
    innerPerson: "=aPerson"
},
link: function (scope, elm, attr){
    // now this change will be reflect in the parent controller also
    scope.innerPerson.name = "not coldstar anymore";
}

编辑:

我还注意到“'isSelected'”如果isSelected是$ scope,则应该是“isSelected”。* entity