Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

javascript - Ng模型不更新控制器值(Ng-model does not update controller value)

Probably silly question, but I have my html form with simple input and button:

(可能是愚蠢的问题,但我的html表单有简单的输入和按钮:)

<input type="text" ng-model="searchText" />
<button ng-click="check()">Check!</button>
{{ searchText }}

Then in the controller (template and controller are called from routeProvider):

(然后在控制器中(从routeProvider调用模板和控制器):)

$scope.check = function () {
    console.log($scope.searchText);
}

Why do I see the view updated correctly but undefined in the console when clicking the button?

(为什么我在单击按钮时看到视图更新正确但在控制台中未定义?)

Thanks!

(谢谢!)

Update: Seems like I have actually solved that issue (before had to come up with some workarounds) with: Only had to change my property name from searchText to search.text , then define empty $scope.search = {};

(更新:好像我其实已经解决了这个问题(必须想出一些解决方法前):只有从改变我的属性名称searchTextsearch.text ,然后定义空$scope.search = {};)

object in the controller and voila... Have no idea why it's working though ;]

(控制器中的对象和瞧...不知道为什么它正在工作;])

  ask by alchemication translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

"If you use ng-model, you have to have a dot in there."

(“如果你使用ng-model,你必须在那里有一个点。”)


Make your model point to an object.property and you'll be good to go.

(让你的模型指向一个object.property,你会很高兴。)

Controller

(调节器)

$scope.formData = {};
$scope.check = function () {
  console.log($scope.formData.searchText.$modelValue); //works
}

Template

(模板)

<input ng-model="formData.searchText"/>
<button ng-click="check()">Check!</button>

This happens when child scopes are in play - like child routes or ng-repeats.

(当孩子范围在游戏中时会发生这种情况 - 如子路线或ng-repeats。)

The child-scope creates it's own value and a name conflict is born as illustrated here :

(子范围创建它自己的值,名称冲突如图所示 :)



See this video clip for more: https://www.youtube.com/watch?v=SBwoFkRjZvE&t=3m15s

(有关详情,请参阅此视频片段: https//www.youtube.com/watch?v = SBwoFkRjZvE&t = 3m15s)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...