由angular指令生成的复选框不响应ng-change

时间:2017-07-12 02:04:34

标签: angularjs angularjs-directive

我的指示:

            (function () {
                var directive = function ($compile, $http, $rootScope, $translate) {
                    return {
                        restrict: 'E',
                        scope: {
                            baseUrl: '@rmsUrl',
                        },
                        link: function (scope, element, attrs) {
                            $rootScope.languageSwitcher = {
                                toggle: true,
                                changeLanguage: function () {
                                    if ($rootScope.languageSwitcher.toggle) {
                                        $translate.use('ENG');

                                    } else {
                                        $translate.use('FRE');
                                    }
                                }
                            }

                            $rootScope.$on('oauth2:authSuccess', function (data) {
                                var html2 = 'French <label class="switch">'
                                html2 += '<input type="checkbox" ng-model="languageSwitcher.toggle" ng-change="languageSwitcher.changeLanguage()" /><div></div>'
                                html2 += '</label>English'
                                element.html(html2);
                                $compile(element.contents())(scope);
                            });

                        }
                    };
                };

                angular.module('testingApp')
                    .directive('rmsLanguageToggler', directive);

            }());

我的索引文件包含指令:

<rms-language-toggler  rms-url='blah blah blah'></rms-language-toggler>

我的问题:

html呈现正确,但更改/单击复选框不会触发该功能:$ rootScope.languageSwitcher.changeLanguage()

1 个答案:

答案 0 :(得分:0)

我现在发现了原因。结果是指令内的ng-change和ng-model仍然引用内部隔离范围。我必须使用$ parent。访问外部模型,即$ parent.languageSwitcher.toggle