標籤:des style blog class code java
本文主要通過介紹ng-click方法來對angularjs中的事件處理方法做個瞭解.
1.切換目錄
git checkout step-10npm 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 seconds7 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還有其它如:
ngMousemove
ngMouseleave
ngMouseover
ngKeyup
ngSubmit
....
可以根據個人需要進行選擇,和JS本身內建的方法差不多,這裡只不過angularjs又多封裝了一層.