access controller scope from Bootstrap-UI Typeahea

2019-02-06 13:26发布

I am unable to call a controller function from inside a custom-template with ui-typeahead:

<input typeahead="val for val in autoComplete($viewValue)"
  typeahead-template-url="searchAutocompleteTpl.html"  
  ng-model="query"/>

<script type="text/ng-template" id="searchAutocompleteTpl.html">
  <span ng-repeat="eqp in match.model.equipment"/>
    <a href="" ng-click="showItem(eqp.model)">
      found in: {{eqp.model}}
    </a>
</script>

The problem is that the controller's scope seems to be absent in the template:

showItem(eqp.model)

is never called. I have also tried with:

$parent.showItem(eqp.model)

to no avail.

How can I call a function/value on the controller's scope then?

4条回答
聊天终结者
2楼-- · 2019-02-06 13:52

The solution of your problem is to initiate an object in your template controller scope like this:

$scope.typeaheadObject = {
   query : '',
}

now in your form you will need to change your ng-model with:

ng-model="typeaheadObject.query'

This will create the object typeaheadObject in all your controller if you don't re-initiate it in one of your controller. So when you will want to access to the content of the object in one of this controller you will just have to do for example:

console.log($scope.typeaheadObject.query)

This is a classical issue in angularJs. You only can access and modify a parent scope if the variable is stock in an object

Finally you have to use a '.' in your ng-model. This will permit your ui-bootstrap module and your own module to share their scope with the object.

I just did an example on plunker to be sure you understand well the issue.

http://plnkr.co/edit/4YWNMagm571Gk2DrCERX?p=preview

Have a good day :)

查看更多
混吃等死
3楼-- · 2019-02-06 13:57

I ran into the same problem and had a look at the typeahead code on github to see if that might offer any clues. It appears that there are several directives involved in the creation of the suggestions list and each gets its own child scope.

In other words, your $parent.showItem(eqp.model) was a good attempt, but you didn't go up enough levels. What worked for me was: $parent.$parent.$parent.showItem(eqp.model)

查看更多
贪生不怕死
4楼-- · 2019-02-06 13:57

It worked for me after adding 4 parents. $parent.$parent.$parent.$parent.

查看更多
在下西门庆
5楼-- · 2019-02-06 14:19

I also have same problem. I'm not sure but its working.

You can use double $parent instead of single.

e.g. $parent.$parent.showItem(eqp.model)

查看更多
登录 后发表回答