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

Unable to bind scope variable of modal from directive angularjs

我无法在模态使用的指令中绑定模态的范围变量。我已经尝试了网上的所有解决方案。我也尝试过 $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>

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

$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 根本不指向控制器范围。