我正在做一个离子应用程序,并在其上创建了我的第一个指令。
指令被正确加载,但是从模板(html)它无法在指令控制器上执行任何函数。
crud_input_fields.html
{{a()}}
crud_input_fields.js
myapp.directive('crudInputFields', function (fieldService) {
return {
restrict: 'E',
replace: true,
templateUrl: '/Content/Mobile/templates/directives/crud/crud_input_fields.html',
scope: {
displayables: '='
},
link: function (scope, element, attrs) {
scope.name = 'crud_input_fields';
scope.a = function () {
console.log('ok');
}
},
controller: function ($scope) {
$scope.a = function () {
console.log('ok');
}
this.a = function() {
console.log('ok');
}
}
}
});
但是,如果我将一个函数放在ui-router Controller上,它可以正常工作:
myapp.controller('CrudInputController', function ($log, $scope, crudContextService,fieldService, schemaService, offlineSchemaService, statuscolorService) {
$scope.a= function () {
console.log('this works!')
}
}
);
该控制器只管理一个页面,该页面依次创建调用指令:
<ion-view title="{{title()}}">
<ion-nav-buttons side="left">
<button class="button-icon icon ion-navicon" menu-toggle="left"></button>
</ion-nav-buttons>
<ion-content has-header="true">
<crud-input-fields displayables="displayables"></crud-input-fields>
</ion-content>
</ion-view>
指令代码:
<fieldset ng-repeat="field in displayables">
{{a()}}
</fieldset>
我已经把所有这些不同的选项(这个,链接,控制器),只是为了测试。
该应用程序使用Ionic和Ripple运行,角度为1.3.15。
任何人都有线索?
答案 0 :(得分:2)
你的指令控制器应该像你这样传递给你的链接函数:
link: function (scope, element, attrs,myDirCtrl)
注意:myDirCtrl
是任意名称,可以称为任何名称
然后你在链接函数中调用你的指令控制器函数,如下所示:
scope.a = function () {
myDirCtrl.a();
}
这是plunk,证明了这一点
答案 1 :(得分:0)
最后,这是由于声明html的方式:
<fieldset ng-repeat="field in displayables" ng-show="!isFieldHidden(field)">
{{a()}}
</fieldset>
没用。
然而,
<fieldset ng-repeat="field in getDisplayables()" ng-show="!isFieldHidden(field)">
{{a()}}
</fieldset>
工作,getDisplayables()fn只返回displayables:
$scope.getDisplayables= function() {
return $scope.displayables;
}
但是,仍然不知道为什么。我知道ng-repeat创建子范围,但这种情况有点微妙,不是吗?