<img ng-src="{{img}}" ng-click="setImage(img)">
这将是巨大的,知道为什么当使用Angular不再被认为“不正确”。
<img ng-src="{{img}}" ng-click="myProfile.setMainImage(img)">
myApp.controller("ProfileController",function($scope,myProfile) { $scope.myProfile = myProfile; });
视图说“当该图像被点击时,它将在myProfile上调用setMainImage()。业务逻辑在myProfile内,在那里它可以测试等。视图只是一个钩子。
在一个更“传统的”或“vanilla”jQuery设置,你必须写下如下:
$("#someId img").on('click',function() { var img = $(this).attr('src'); myProfile.setMainImage(img); // where does myProfile come from here? // how does it update the view? });
当然,JavaScript社区已经确定以这种方式编写大型应用程序并不真正可行,部分原因是视图和模型对象之间的断开(如代码片段中的注释所指示的),这就是为什么我们有像Angular这样的框架。
所以,我们知道这个原生的jQuery代码是不理想的,但我们仍然不确定整个ngClick事情。让我们将它与另一个非常流行的JavaScript框架进行比较,它提供了一个MV *架构,Backbone。在最近的RailsCasts插曲AngularJS,someone asked a very similar question:
Is it just me,or AngularJS looks so a bad idea? Ryan,don’t get me wrong,the episode was great,but I’m not convinced by the framework.
All that
ng-show
,ng-repeat
,ng-class
are looking like the old Java’s JSF,and similar frameworks. It also enforces obtrusive JS withng-submit
andng-click
.So my point is: your view will easily become cluttered and totally dependent on it. The advantage of other frameworks like Backbone,is to have a separation of concerns between the presentation and the behavior (less or no dependencies),and a structured client side application (MVVM).
My response此处也适用:
In a framework like Backbone,you’d have something like the following code (taken from the Backbone website,minus a few lines):
06003
In this object which is a view,you are setting up event handlers on varIoUs elements. These event handlers call functions on the view object,which delegate to models. You also set up callbacks on varIoUs model events (such as
change
) which in turn call functions on the view object to update the view accordingly.In Angular,the DOM is your view. When using
ng-click
,ng-submit
,etc.,you are setting up event handlers on these elements,which call functions that should delegate to model objects. When usingng-show
,etc. you are setting up callbacks on model events that change the view.The fact that AngularJS sets up these [hooks and] callbacks behind the scenes for you is irrelevant; the only difference between this and something like Backbone is that Angular lets you write your view declaratively–you describe what your view is–rather than imperatively–describing what your view does.
So,in the end,
<a ng-click="model.set({selected: true})">
really adds no more dependencies than06004
…but it sure is a hell of a lot less code. 原文链接:https://www.f2er.com/angularjs/146463.html