2016-09-06 74 views
0

我有一个配置文件更新指令,我想从父范围触发更新动作。 这里是什么样子的我的代码:将指令动作绑定到父控制器AngularJS

main.js

angular.module('app') 
.directive('profile',{ 
    scope: { 
     updateFromDirective: "=" 
    }, 
    template: '<form><input ng-model="name"/></form>', 
    controller: function(){ 
     this.updateFromDirective = function(){ 
      /* update here */ 
     }; 
    } 
}) 
.controller('Ctrl', function(){ 
    this.updateFromController = function(){ 
     if(condition){ 
      /* how do I call updateFromDirective here ??? */ 
     } 
    }; 
}); 

的index.html

<div ng-controller="Ctrl"> 
    <profile updateFromDirective="updateFromController"></profile> 
    <button ng-click="updateFromController()">Update</button> 
</div> 
+0

正是你在这里做什么?什么是错误? –

+0

当点击更新触发器updateFromController时,然后调用updateFromDirective,它在将updateFromDirective传递给rootScope时共同工作 – Ayoub

+0

共享plunker示例,所以我会看到错误在哪里gettting。 –

回答

2

传递你的函数参考使用'&'如果定向你通过这样的updateFromController()使用别的'='updateFromController(既会工作)

现在你的情况

注:我假设你不希望因为你有你的函数使用$范围在这个

控制器要呼叫指令,你需要把它作为一个回调控制器功能,并可以调用回调像下面

angular.module('app',[]) 
.controller('Ctrl', function(){ 
    this.updateFromController = function(){ 
     alert('In Contrller') 
    }; 
}).directive('profile',function(){ 
    return{ 
    scope:{ 
     controllercallback: "&" 
    }, 
    template:'<input ng-model="name"/><br/><button ng-click="ctrl.updateFromDirective()">Update</button>', 
    controller:function(){ 
     this.updateFromDirective=function(){ 
     alert('In Directive') 
     this.controllercallback(); 
     } 
    }, 
    bindToController: true, 
    controllerAs:'ctrl' 
    } 

}) 

你的HTML应该如下面

<div ng-controller="Ctrl as vm"> 
<profile controllercallback="vm.updateFromController()"></profile> 

但在这里你的按钮是指令本身。

如果你不想让你的按钮是由角给你的指令,你可以使用发布/订阅模式的一部分,像下面

angular.module('app',[]) 
.controller('Ctrl', function($scope){ 
    this.updateFromController = function(){ 
     $scope.broadcast('calldirective'); 
    }; 
}).directive('profile',function(){ 
    return{ 
    template:'<input ng-model="name"/>', 
    controller:function($scope){ 
     $scope.$on('calldirective', function() { 
     alert('In Directive') 
     }); 

    } 



} 

}) 
+0

如何在updateFromController内调用updateFromDirective? – Ayoub

+0

谢谢@Rishi,但问题是该按钮不在指令的模板上 – Ayoub

+0

更新了我的答案,为您的案件.. –