0

次のコードがあります。

<div id='parent'>
   <div id='child1'>
      <my-select></my-select>
   </div>
   <div id='child2'>
      <my-input></my-input>
   </div>
</div>

また、データ ファクトリからデータを取得する 2 つのディレクティブもあります。選択ボックスの値が変更されると、それに応じて入力が変更されるように、2 つのディレクティブが互いに対話する必要があります。

これが私の2つのディレクティブです:

.directive("mySelect", function ($compile) {
    return {
        restrict: 'E',
        scope:'=',
        template: " <select id='mapselectdropdown'>\
                        <option value=map1>map1</option> \
                        <option value=map2>map2</option> \
                    </select>'",
        link: function (scope, element, attrs) {
            scope.selectValue = //dont konw how to get the value of the select
        }
    };
})
.directive("myInput", function($compile) {
    return {
        restrict: 'E',
        controller: ['$scope', 'dataService', function ($scope, dataService) {
            dataService.getLocalData().then(function (data) {
                $scope.masterData = data.input;
            });
        }],
        template: "<input id='someInput'></input>",
        link: function (scope, element, attrs) {
            //here I need to get the select value and assign it to the input 
        }
    };
})

これは基本的に、選択時に追加できる onchange() 関数を実行します。何か案は?

4

3 に答える 3

1

$rootScope他のコントローラーがリッスンするメッセージをブロードキャストするために使用できます。

// Broadcast with
$rootScope.$broadcast('inputChange', 'new value');

// Subscribe with
$rootScope.$on('inputChange', function(newValue) { /* do something */ });

ここでAngularのドキュメントを読む

于 2015-04-12T01:59:47.427 に答える
0

多くの研究の後、これはうまくいったものです...

以下を追加しました。

.directive('onChange', function() {    
        return {
            restrict: 'A',
            scope:{'onChange':'=' },
            link: function(scope, elm, attrs) {            
                scope.$watch('onChange', function(nVal) { elm.val(nVal); });            
                elm.bind('blur', function() {
                    var currentValue = elm.val();                
                    if( scope.onChange !== currentValue ) {
                        scope.$apply(function() {
                            scope.onChange = currentValue;
                        });
                    }
                });
            }
        };        
    })

次に、要素のリンク関数に次を追加しました。

link: function (scope, elm, attrs) {
    scope.$watch('onChange', function (nVal) {
       elm.val(nVal);
    });
}

最後に、スコープ内で値が設定される属性を追加しました。

<select name="map-select2" on-change="mapId" >
于 2015-04-17T16:14:12.333 に答える
0

たぶん、共有変数を定義する外側のスコープのプロパティにアクセスするためのディレクティブをトランスクルードしますか?

このtranscludeオプションは正確には何をしますか? transclude は、このオプションを指定したディレクティブの内容が、ディレクティブの内部ではなく外部のスコープにアクセスできるようにします。

-> https://docs.angularjs.org/guide/directive

于 2015-04-12T07:33:42.387 に答える