本文主要通过介绍ng-click方法来对angularjs中的事件处理方法做个了解.
1.切换目录
git checkout step-10
npm start
2.效果
点击右边的小图片,那么左边框中将显示大图片,示例如下:
3.代码实现
查看step-9和step-10之间的代码差异:https://github.com/angular/angular-phonecat/compare/step-9...step-10
Controllers(控制器)
app/js/controllers.js
:
‘use strict‘;/* Controllers */
var phonecatControllers = angular.module(‘phonecatControllers‘, []);
phonecatControllers.controller(‘PhoneListCtrl‘, [‘$scope‘, ‘$http‘,
function($scope, $http) {
$http.get(‘phones/phones.json‘).success(function(data) {
$scope.phones = data;
});$scope.orderProp = ‘age‘;
}]);phonecatControllers.controller(‘PhoneDetailCtrl‘, [‘$scope‘, ‘$routeParams‘, ‘$http‘,
function($scope, $routeParams, $http) {
$http.get(‘phones/‘ + $routeParams.phoneId + ‘.json‘).success(function(data) {
$scope.phone = data;
$scope.mainImageUrl = data.images[0];
});$scope.setImage = function(imageUrl) {
$scope.mainImageUrl = imageUrl;
}
}]);
注:控制器这里定义了一个setImage方法,就是将mainImageUrl的值设置为当前imageUrl.
CSS(样式)
app/css/app.css
ul.phone-thumbs img:hover {
cursor: pointer;
}
改变鼠标移动上去的样式为指针形.
Template(模板)
app/partials/phone-detail.html
<img ng-src="{{mainImageUrl}}" class="phone">...
<ul class="phone-thumbs">
<li ng-repeat="img in phone.images">
<img ng-src="{{img}}" ng-click="setImage(img)">
</li>
</ul>
...
这里定义了一个ng-click方法,这里将当前的img作为参数传过去,然后,setImage方法将mainImageUrl的值替换为当前点击的图片,从而实现点击小图片,左边的图片被放大.
4.测试:
test/e2e/scenarios.js
...
describe(‘Phone detail view‘, function() {...
it(‘should display the first phone image as the main phone image‘, function() {
expect(element(by.css(‘img.phone‘)).getAttribute(‘src‘)).toMatch(/img\/phones\/nexus-s.0.jpg/);
});it(‘should swap main image if a thumbnail image is clicked on‘, function() {
element(by.css(‘.phone-thumbs li:nth-child(3) img‘)).click();
expect(element(by.css(‘img.phone‘)).getAttribute(‘src‘)).toMatch(/img\/phones\/nexus-s.2.jpg/);element(by.css(‘.phone-thumbs li:nth-child(1) img‘)).click();
expect(element(by.css(‘img.phone‘)).getAttribute(‘src‘)).toMatch(/img\/phones\/nexus-s.0.jpg/);
});
});
执行如下命令进行测试:
npm run protractor#测试结果如下:
------------------------------------
PID: 4250 (capability: chrome #1)
------------------------------------Using ChromeDriver directly...
.......Finished in 9.867 seconds
7 tests, 11 assertions, 0 failures
5.实验:
在Controllers中的PhoneDetailCtrl加入:
$scope.hello = function(name) {
alert(‘Hello ‘ + (name || ‘world‘) + ‘!‘);
}
同时在phone-detail.html中加入:
<h1>{{phone.name}}</h1>
<button id="{{phone.name}}" ng-click="hello(phone.name)">Hello</button>
<p>{{phone.description}}</p>
...
效果如下图所示:
这样就完成了一个ng-click的操作.
事件处理方法,除了ng-click还有其它如:
....
可以根据个人需要进行选择,和JS本身自带的方法差不多,这里只不过angularjs又多封装了一层.
AngularJS学习--- 事件处理(Event Handlers) ng-click操作 step 10