[英]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. 我想知道是否有人可以帮助我创建一个新指令,以便在从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. 一切正常,我可以使用
{{ myValue }}
将值写入HTML页面,甚至可以在输入上使用ng-model
,它返回值。
But for some reason, if I try to access the variable via the controller $scope.myValue
is undefined
? 但是由于某种原因,如果我尝试通过控制器访问变量
$scope.myValue
是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!. 我已经创建了一个插件(不从webServer加载数据,而是加载基本列表值),但这似乎可行,而我的项目却不起作用,因为从项目中复制了它,所以我没有得到! 。
If anyone has any ideas, I would really appreciate hearing them. 如果有人有任何想法,我将不胜感激。
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? 您说要从webServer加载它,是否可能是您在尝试将变量分配给后端数据之前使用该变量?
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. 这个想法是在后端AJAX请求完成后打印变量值。 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. 它会打印出比使用
$watch
函数所需要的值更正确的值,以及在达到预期值后将对该变量执行的操作。
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
希望这对别人有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.