简体   繁体   中英

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>

You said you are loading it from webServer, could it be that you are trying to use that variable before the data from the back-end was assigned to it?

I would suggest to use something like:

$scope.$watch("myValue", function (newVal) {console.log(newVal);})

or:

$timeout(function () {console.log($scope.myValue);}, 5000)

The idea is to print the variable value after the back-end AJAX request finished. It it will print the correct value than you have to use the $watch function and to what you need to do with the variable after it has the expected value.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM