AngularJS - 隔离范围绑定到父范围

时间:2013-04-24 14:15:00

标签: angularjs

如果我的“父”页面中有html元素,那么:

   <div ng-include"'Go-To-Child-Page.html'" />

我的孩子/包含页面是这样的:

   <some-directive two-way-binding="$parent.SomeParentScope"></some-directive>

为什么这不符合我的指令?或者更好的是,我如何让它发挥作用?

 app.directive ('someDirective', function(){
    return {
        retrict: 'E',
        replace: true,
        scope: {
            myBinding : "=twoWayBinding",  <- this is what is not working
        },
        template: '<select ng-model="myBinding" ng-options="myType.Description for myType in myTypes"></select>'
    };
}

修改更新:

为什么我发布这个问题?

在完成一个非常冗长的表格后,我立刻注意到我有很多类似的控件,我编码器说我应该抽象出来。其中之一是精选控制。这种控制涉及两种情况:

(1)用户必须在填充选择控件之前选择过滤器;和

(2)代码预先定义了选择控件的过滤器。

这两种情况的解决方案如下所示。我希望这有助于每个人,因为我真的很喜欢使用Angular,它提供的指令功能来创建“Html-magic”是惊人的。

2 个答案:

答案 0 :(得分:1)

你似乎在不必要地做了很多事情,但那可能是因为我误解了你的目标。

我在这里修复了你的plnkr:http://plnkr.co/edit/FqpzC5p1Ogm4attYiArV?p=preview

必要的基本变化似乎是:

  1. 将选定的过滤器(后部/前部)传递到指令
  2. ngOptions替换为ngRepeat和过滤器
  3. 您的指令实际上不需要控制器(通常大多数指令应该使用链接器函数)。我删除了一些内容以使其更简单,但您仍然可以按原样连接$scope.filterTypes(从$scope.myTypes中提取可用类型)并且它仍然可以正常工作。

    <强>更新

    由于你没有详细说明你的所有要求,我可能会遗漏一些要求,但这个实现是我收集你正在寻找的:

    http://plnkr.co/edit/pHgJ84Z35q5jxCpq3FHC?p=preview

    它有动态过滤,它不是不必要地使用控制器,它有双向绑定。唯一的问题是它引用了“描述”字段(就像你原来的那样)。如果您愿意,可以使用HTML进行配置。

答案 1 :(得分:0)

场景1:让用户过滤:

Filter: 
<input type="radio" ng-model="choice.type" value="Rear"> Rear
<input type="radio" ng-model="choice.type" value="Front"> Front
<br>
Select:
<name-value-select selected-item="selected.item" choice="choice.type" options="axleTypes"></name-value-select>

场景2:代码中的预过滤:

<name-value-select preselected-filter="Front" selected-item="selected.item" options="axleTypes"></name-value-select>

两种情况的指令:

.directive('nameValueSelect', function () {
  return {
    replace: true,
    restrict: "E",
    scope: {
        selectedItem: "=",
        choice: "=",
        options: "=",
        preselectedFilter: "@"
    },
    controller: function ($scope) {
        $scope.$watch('choice', function (selectedType) {
            $scope.selectedItem = '';  // clear selection
            $scope.filterTypes = [];
            angular.forEach($scope.options, function (type) {
                if ($scope.preselectedFilter !== undefined) {
                    selectedType = $scope.preselectedFilter;
                }
                if (type.Type === selectedType) {
                    this.push(type);
                }
            }, $scope.filterTypes);
            $scope.filterTypes.sort(function (a, b) {
                return a.Description.localeCompare(b.Description);
            });
        });
    },
    template: '<select  ng-model="selectedItem"  ng-options="o.Description for o in filterTypes"><option value="" selected="selected">Please Select </option></select>'
}; 
 });

众所周知的强制性掠夺者:

http://plnkr.co/edit/tnXgPKADfr5Okvj8oV2S

相关问题