2017-02-14 5 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>

ここでは、$scope.ControllerVarとしてあなたのコントローラでControllerVarを使用することができますを観察下に変数を持っています。

+0

ありがとうございます。 scope.myValの値をコントローラに渡すにはどうすればいいですか? –

+0

''を '

'に変更し、 'restrict: 'A'' – nivas

+0

を' $ scope.ControllerVar'をコントローラ内で使うと、 'scope'と同じ値になります。 myVal'の指示に従います。 –

関連する問題