双向绑定隔离范围在自定义指令 - AngularJS中不起作用

时间:2016-08-03 09:44:54

标签: javascript angularjs

最近我将角度版本1.2迁移到了1.5.x

我面临的问题是隔离的范围元素在自定义指令中没有绑定。我调试时无法看到$scope.menuitems,导致menu.menuitems为" undefined"。

    Directive:
    angular.module('myapp')
            .directive('menuSelect', menuSelect);
        function menuSelect() {
            var directive = {
                link: linkFunc,
                controller: menuselectController,
                controllerAs: 'menu',
                restrict: 'A',
                replace: true,
                bindToController: true,
                require: '^form',
                scope: {
                    menuitems: '=',
                    showError: '=',
                    ismenuSelectionAllowed: '=',
                    onMenuitemChange: '&',

                },
                templateUrl: 'scripts/NavMenu/menuSelect/menuSelect.html'
            };
            return directive;
            function linkFunc(scope, el, attr, frm) {
                var menu = scope.menu;
                menu.menuForm = frm;
                menu.selectmenu = function() {
                    menu.menuSelectionChanged();
                };
            }
        }
    menuselectController.$inject = ['$scope', '$filter'];
        function menuselectController($scope, $filter) {
            var menu = this;
            var watcher2, categories = null;
            menu.menuitems = $scope.menuitems;  //I'm seeing the $scope doesn't bind the isolated elements.
            menu.filter = null;
            menu.selected = null;
            menu.addFeature = addFeature;
            menu.removeFeature = removeFeature;
            -----
        -----
    }

指令调用的HTML:

    <div data-menu-select data-menuitems="menuitems" data-show-error="formAction=='Submit'"
                             data-is-menu-selection-allowed="menuSelectionAllowed"
                             data-on-menuitem-change="featureChanged()"></div>

1 个答案:

答案 0 :(得分:0)

您使用控制器作为语法。在这种情况下,您的隔离范围属性将绑定到控制器中的 this 以及 $ scope.menu ,因此您不需要此行

menu.menuitems = $scope.menuitems; 

它只是 menu.menuitems 未定义,只需删除此行或debugg以查看 menu.menuitems 行之前已包含您在中传递的值html模板中的data-menuitems 属性。在此处了解有关控制器的更多信息https://docs.angularjs.org/api/ng/directive/ngController

所以它更像是

function menuselectController($scope, $filter) {
  var menu = this;
  var watcher2, categories = null;
  menu.filter = null;
  menu.selected = null;
  menu.addFeature = addFeature;
  menu.removeFeature = removeFeature;
  ----------
}

另请参阅此快速编写的代码,我确实说明 menu.menuitems 已包含您需要的内容,它会显示警报,以便您可以看到值是什么。它使用1.5.5角。

http://codepen.io/kmlzjc/pen/oLPQxa