无法从指令angularjs绑定模态的范围变量

时间:2016-01-30 06:21:48

标签: javascript angularjs bootstrap-modal

我无法在模态使用的指令中绑定模态的范围变量。我已尝试过网上的所有解决方案。我也尝试了$parent解决方案,但似乎没有任何效果。我是Angularjs的新手,所以请帮帮我。以下是代码:

指令:

.directive('searchPart', function($timeout) {
        return {
            restrict: 'AEC',
            transclude:true,
            scope: {
                items: '=',
                prompt:'@',
                title: '@',
                subtitle:'@',
                model: '=',
                onSelect:'&'
            },
            link:function(scope,elem,attrs){
                scope.handleSelection=function(selectedItem){
                    scope.model=selectedItem;

                    scope.current=0;
                    scope.selected=true;
                    $timeout(function(){
                        scope.onSelect();
                    },200);
                };
                scope.current=0;
                scope.selected=true;
                scope.isCurrent=function(index){
                    return scope.current==index;
                };
                scope.setCurrent=function(index){
                    scope.current=index;
                };
            },
            templateUrl: 'admin/product/catalogView/partSearch.html'
        }
    })

模态控制器:

.controller('ChildPartEditCtrl', function ($scope, $modalInstance, Data, $http) {
        $scope.name="";
        $scope.onItemSelected=function(){
            console.log('selected='+$scope.name);
        }}

HTML:

 <search-part items="items" prompt="Enter full part number" title="name" subtitle="abbreviation" model="name" on-select="onItemSelected()" />

模板

<input type="text" ng-model="model" placeholder="{{prompt}}" ng-keydown="selected=false" />
<br/>
<div class="items" ng-hide="!model.length || selected">
    <div class="item" 
      ng-repeat="item in items | filter:{partnumber:model}  track by $index" 
      ng-click="handleSelection(item.partnumber)" style="cursor:pointer" 
      ng-class="{active:isCurrent($index)}" 
      ng-mouseenter="setCurrent($index)">
        <p class="title">{{item.partnumber}}</p>
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

问题似乎在于您将原始值分配给模型。您应该在控制器中有一个对象,例如:

$scope.selected = {name: ''}

然后传递selected作为模型:

<search-part items="items" prompt="Enter full part number" title="name" subtitle="abbreviation" model="selected" on-select="onItemSelected()" />

并在指令中设置scope.model.name=selectedItem,这应该有用。

这是有效的,因为对象是按值传递的,对象引用(内存位置)作为值。因此scope.model将指向控制器范围selected对象。 scope.model.name=selectedItem会更新name财产。

原语按照它的实际值传递,在原始代码中,scope.model根本没有指向控制器范围。