[英]Unable to bind scope variable of modal from directive angularjs
I am having trouble binding the scope variable of a modal in a directive used by the modal. 我在绑定模态的作用域变量到模态使用的指令时遇到麻烦。 I have tried all the solutions on the net. 我已经在网上尝试了所有解决方案。 I have tried the $parent
solution too, but nothing seems to work. 我也尝试了$parent
解决方案,但似乎没有任何效果。 I am new to Angularjs, so please help me out. 我是Angularjs的新手,所以请帮助我。 Below is the code : 下面是代码:
directive: 指示:
.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'
}
})
modal controller: 模态控制器:
.controller('ChildPartEditCtrl', function ($scope, $modalInstance, Data, $http) {
$scope.name="";
$scope.onItemSelected=function(){
console.log('selected='+$scope.name);
}}
html: 的HTML:
<search-part items="items" prompt="Enter full part number" title="name" subtitle="abbreviation" model="name" on-select="onItemSelected()" />
Template 模板
<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>
The issue seems to be that you're assigning a primitive value to model. 问题似乎在于您正在为模型分配原始值。 You should have an object in controller, for example: 您应该在控制器中有一个对象,例如:
$scope.selected = {name: ''}
then pass selected
as the model: 然后通过selected
作为模型:
<search-part items="items" prompt="Enter full part number" title="name" subtitle="abbreviation" model="selected" on-select="onItemSelected()" />
and set scope.model.name=selectedItem
in the directive, that should work. 并在指令中设置scope.model.name=selectedItem
,它应该可以工作。
This works because objects are passed by value, with the objects reference (memory location) as value. 之所以可行,是因为对象是通过值传递的,而对象引用(内存位置)是值。 So scope.model
will point to the controller scopes selected
object. 因此, scope.model
将指向控制器作用域selected
对象。 scope.model.name=selectedItem
will update it's name
property. scope.model.name=selectedItem
将更新其name
属性。
Primitives are passed by it's actual value, in your original code, scope.model
doesn't point to controllers scope at all. 基元是通过它的实际值传递的,在您的原始代码中, scope.model
根本不指向控制器的作用域。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.