2017-02-14 155 views
1

如何將指令的值傳遞給控制器​​或將指令中的變量傳遞給控制器​​。謝謝。將指令中的變量傳遞給控制器​​

這是我的代碼。它具有$下的變量觀察功能

.directive("groupId", function() { 
    return { 
    replace: true, 
    link: function(scope, element, attrs) { 
     attrs.$observe('groupId', function(value) { 
     myVal = value; 
     }); 
    } 
    }; 
}) 
+2

需要將範圍定義添加到指令 –

回答

1

<!DOCTYPE html> 
 
<html ng-app="plunker"> 
 

 
<head> 
 
    <script data-require="[email protected]" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script> 
 
</head> 
 

 
<body ng-controller="MainCtrl"> 
 
    <table> 
 
    <!--* groupIdValue value is passing from controller to directive 
 
    * and my-val is returned back from directive to controller 
 
    * that value is available to controller from ControllerVar variable *--> 
 
    <tr group-id="{{groupIdValue}}" my-val="ControllerVar"></tr> 
 
    </table> 
 
    controller variable: {{ControllerVar}} 
 
</body> 
 
<script> 
 
    var app = angular.module('plunker', []); 
 

 
    app.controller('MainCtrl', function($scope) { 
 
    $scope.groupIdValue = '123345'; 
 
    }).directive("groupId", function() { 
 
    return { 
 
     replace: true, 
 
     restrict: 'A', 
 
     scope: { 
 
     myVal: "=myVal" 
 
     }, 
 
     link: function(scope, element, attrs) { 
 
     attrs.$observe('groupId', function(value) { 
 
      scope.myVal = value; 
 
     }); 
 
     } 
 
    }; 
 
    }) 
 
</script> 
 

 
</html>

在這裏,您可以使用ControllerVar在控制器$scope.ControllerVar

+0

的聲明謝謝。我如何將scope.myVal值傳遞給控制器​​,我將如何調用它? –

+0

變化'<組ID我-VAL = 「ControllerVar」>''到'

和使用'限制:'A'' – nivas

+0

使用'$ scope.ControllerVar'內部控制器,它將具有範圍的'相同的值。 myVal'內部指令。 –

相關問題