我是Angular的新手。请考虑以下代码。
<form name="newEventForm">
<fieldset>
<label for="eventName">Event Name:</label>
<input id="eventName" required ng-model="event.name" type="text" placeholder="Name of your event...">
<button ng-click="saveEvent(event, newEventForm)" type="submit" class="btn btn-primary">Save</button>
<button ng-click="cancelEdit()" type="button" class="btn btn-default">Cancel</button>
</form>
我的问题是 - 为什么我们需要将event参数传递给saveEvent函数?不使用ng-model自动通过Angular端的双向绑定生成event.name变量? e.g。
<form name="newEventForm">
<fieldset>
<label for="eventName">Event Name:</label>
<input id="eventName" required ng-model="event.name" type="text" placeholder="Name of your event...">
<button ng-click="saveEvent( newEventForm)" type="submit" class="btn btn-primary">Save</button>
<button ng-click="cancelEdit()" type="button" class="btn btn-default">Cancel</button>
</form>
在代码的第二个版本中,我没有明确地将事件作为函数参数注入。但是,按下提交时,这是saveEvent的代码
$scope.saveEvent = function(newEventForm)
{
alert(1);
alert(newEventForm.$valid);
if(newEventForm.$valid)
{
window.alert('event ' + event.name + ' saved!');
}
}
并且事件未定义。不应该定义吗?如果问题是新手的问题,请道歉。只是试图了解如何通过ng-model创建范围项,以及双向绑定如何工作。谢谢!
更新
Doh,我应该使用$ scope.event。然后它工作。谢谢,就像我说的那样 - 对此我不熟悉,在我提出这个问题之后,我才明白了这一点:)
答案 0 :(得分:1)
视图在关联范围下创建事件变量,使用$ scope.event.name。 祝你好运
答案 1 :(得分:0)
Actually all variable or model which are specified in the html are scope
variable.
Example
<div ng-controller="myController" ng-init="name='Hello World'">
{{name}}
<button ng-click="myFn(name)"> Click Me </button>
</div>
In this example, I have initiated a variable called name
. It is actually a scope variable. This code will actually like
myApp.controller("myController", function($scope){
$scope.name = "Hello World";
$scope.myFn = function(param){
// here you can see that your variable name passed from html is same as your scope variable
if(param == $scope.name){
alert("Yes, two are equal !!!");
}
}
});
This two are same. You can either use html or js.