Search code examples
javascriptangularjsangularjs-directiveangularjs-scopeangular-ui-bootstrap

Angular scope variable available on html page but not controller?


I wonder if anyone could help me I have created a new directive so I can filter a dropdown list while loading data from a webServer. It all works fine, and I can write the values to the HTML page using {{ myValue }}, and I can even use ng-model on an input, and it returns the value.

But for some reason, if I try to access the variable via the controller $scope.myValue is undefined?

I have created a plunker (doesn't load data from webServer but just loads basic list values instead), but this seems to work, and my project doesn't, which I don't get as I have copied it from my project!.

If anyone has any ideas, I would really appreciate hearing them.

Plunker

On my page I have

<div search-dropdown text="myText" value="myValue"></div>

The directive is

<div class="btn-group searchDropdown">
    <button type="button" class="btn btn-default">
        <input search-dropdown-input type="text" placeholder="Enter name to search..." ng-model="filterText" ng-change="filter();" />
    </button>
    <button search-dropdown-toggle type="button" class="btn btn-default dropdown-toggle">
        <span class="caret"></span>
        <span class="sr-only">Split button!</span>
    </button>
    <ul class="dropdown-menu" role="menu">
        <li ng-repeat="item in items"><a href="javascript:void(0);" ng-click="selectItem($index);">{{ item.name }}</a></li>
    </ul>
</div>

Solution

  • It appears that all is fine. The only difference was my angular version.

    To fix my version I used an object to pass into my directive instead of two separate variables.

    So now my directive properties are populated like so

    Text="myObj.text" value="myObj.value"
    

    I guess the "reference" to the variables was somehow lost?

    Had a similar problem before and this was recommended. I only remembered after I posted on here. Hope this helps someone else