2017-07-18 58 views
-1

我在控制器中有一個函數,我想通過單擊按鈕(指令中的按鈕)從指令調用該函數。我在按鈕上有一個ng-click,它有一個應該調用控制器功能的功能。但傳遞給控制器​​的值是未定義的。我究竟做錯了什麼?我加入了代碼中的註釋來幫助理解傳遞給綁定到指令的函數的值未定義

這是指令:

ebApp.directive('monthDir', function() { 
    return { 
     restrict: 'E', 
     templateUrl: 'htmlFiles/monthDirective.html', 
     transclude: true, 
     scope: { 
      ebObj: "=obj", 
      onCl : "&" //bind function 
      //countArraysc: "=countObj" 
     }, 
     link: function (scope, element, attrs) { 
      scope.removeDir = function (removeVal) { //directive's ng-click to call controller function 
       console.log(removeVal); //shows value here but undefined in controller 
       scope.onCl(removeVal); //calling controller function 
      } 

     }, 
     controller: function ($scope) { 
      console.log($scope); 
     } 
    } 
}) 

該指令的與ng-click HTML中應該調用哪個應該調用控制器功能功能:

div class="row monthDirC"> 
<div class="form-group"> 
    <span class="glyphicon glyphicon-remove-sign pull-right cursorC" 
      ng-click="removeDir(ebObj.costArray[count])"></span> 
    <label for="datepick" class="col-md-6">Select month</label> 

使用該指令的HTML:

<month-dir ng-repeat="count in countArray" on-cl="removeDirCtrl(removeVal)" obj="ebObj.costArray[count]"> 
      <ng-transclude></ng-transclude> 
     </month-dir> 

控制器功能:

$scope.removeDirCtrl = function (removeVal) { // function to be called from directive 
    console.log("ctrlRemove"); 
    console.log(removeVal); //undefined 
} 
+0

變更爲呼叫控制器如下指令代碼:scope.removeDir =函數(removeVal){//指令的納克點擊呼叫控制器功能 console.log(removeVal); //在此處顯示值,但在控制器中未定義 scope.onCl({removeVal:removeVal}); //調用控制器功能 } – Harpreet

+0

@Harpreet。我看不懂。你能回答嗎? – Abhi

回答

0

更改指令代碼如下:

scope.removeDir = function (removeVal) { 
    console.log(removeVal); 
    scope.onCl({removeVal: removeVal}); 
} 

Focus在傳遞到回調scope.onCl參數爲{removeVal:removeVal}

0

,如果你只是想打電話給在controller一個function你不必複雜化directive這麼多

var app = angular.module('app', []); 
 
app.controller('customctrl', function($scope) { 
 
    $scope.callMe = function(name) { 
 
    alert('Hey ' + name + '! the time now is ' + new Date()); 
 
    } 
 
}); 
 
app.directive('monthDir', function() { 
 
    return { 
 
    restrict: 'E', 
 
    template: `<input type="text" placeholder="what is your name?" data-ng-model="name"></input> 
 
    <br/><hr /> 
 
    <input type="button" value="what is the time ?" data-ng-click="callMe(name)"></input>`, 
 
    link: function(scope, element, attrs) { 
 
     scope.name = 'there'; 
 
    }, 
 
    controller: 'customctrl' //the pre-defined controller name 
 
    } 
 
});
<!DOCTYPE html> 
 
<html ng-app="app"> 
 

 
<head> 
 
    <link rel="stylesheet" href="style.css"> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> 
 
    <script src="script.js"></script> 
 
</head> 
 

 
<body ng-controller='customctrl'> 
 
    <month-dir></month-dir> 
 
</body> 
 

 
</html>

相關問題