0

我有以下代码:

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

我还有两个从数据工厂获取一些数据的指令。I need the two directives to talk to each other such that when a value in select box is changed the input in changes accordingly.

这是我的两个指令:

.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

也许包含指令以访问您定义共享变量的外部范围的属性?

这个嵌入选项到底有什么作用?transclude 使带有此选项的指令的内容可以访问指令外部而不是内部的范围。

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

于 2015-04-12T07:33:42.387 回答
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 回答