gpt4 book ai didi

javascript - 为什么我的 ng-model 变量在 Controller 中未定义?

转载 作者:可可西里 更新时间:2023-11-01 01:56:07 26 4
gpt4 key购买 nike

我在 angular js 项目中遇到 $scope 问题。例如,当我在输入字段上使用 ng-model="modelExample"时,我无法使用 $scope.modelExample 在我的 js 中访问它。有没有其他人遇到过类似的问题?

这很奇怪,调用了一个函数但 ng-model 没有绑定(bind)。请参阅下面的代码,当我提交表单时调用函数 refreshResults() 但 $scope.search 返回未定义。

angular.module('starter', 
['ionic',
'starter.controllers',
'starter.filters',
'akoenig.deckgrid',
"angucomplete",
// 'ui.bootstrap',
'starter.services'])

.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})

.state('app.browse', {
url: "/browse",
views: {
'menuContent' :{
templateUrl: "templates/browse.html",
controller: 'BrowseCtrl'
}
}
})

.state('app.search', {
url: "/search",
views: {
'menuContent' :{
templateUrl: "templates/search.html",
controller: 'SearchCtrl'
}
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/browse');
});


angular.module('starter.controllers', [])
.controller('SearchCtrl', function($scope) {
$scope.refreshResults = function() {
console.log($scope.search);
};
})


<ion-view>
<ion-content class="has-header">
<form ng-submit="refreshResults()" class="bar bar-header item-input-inset">
<label class="item-input-wrapper">
<i class="icon ion-ios7-search placeholder-icon"></i>
<input type="search" placeholder="Search..." ng-model="search">
</label>
</form>
</ion-content>
</ion-view>

最佳答案

@DavidTryon 在评论中解决了我的问题。我用错了范围。我需要使用一个对象而不是一个字符串。换句话说,我需要做一些类似 ng-model="search.term" 而不是 ng-model="search" 的事情,然后像这样在 js 中使用它:$scope.search.term。它与继承有关,但长话短说,如果您的 ng-model 中没有点 (.),则说明您做错了。

这里有更多信息: http://jimhoskins.com/2012/12/14/nested-scopes-in-angularjs.html

谢谢大卫!

汤姆

关于javascript - 为什么我的 ng-model 变量在 Controller 中未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23455718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com