Angular Scope

  • Scope є об'єктом, який відноситься до моделі додатку
  • Це основа двостороннього зв'язку Angular між видом та контролером

 

  • Контролер може встановлювати властивості Scope
  • Вид зв'язується з властивостями, встановленими контролером
  • Angular зобов'язаний їх синхронізувати

$rootScope

  • Батьківський scope називається $ rootScope, який Angular створює при старті додатку
  • Angular рухається по DOM і створює нові scope коли зустрічає деякі директиви (ng-controller, наприклад, створює новий scope )
  • Дерево scope схоже на дерево DOM
<button ng-click="viewComment()">
    {{ showComment ? 'Hide comment &raquo;' : 'View comment &raquo;' }} 
</button>
$scope.showComment = false;

$scope.viewComment = function() {
     $scope.showComment = !$scope.showComment;
}
<script src="vendor/angular-animate/angular-animate.js"></script>

<script src="vendor/angular-ui-bootstrap/ui-bootstrap-tpls-1.3.3.js"></script>
'ngAnimate','ui.bootstrap'
<div class="well well-lg" uib-collapse="!showComment">

</div>

Angular Form Validation

  • Вимкнути валідацію HTML5:

<form class="form-horizontal” name="bookForm”

ng-submit="sendBook()" novalidate>

  • Angular бере відповідальність за валідацію
  • Ім’я форми обов’язкове
  • ng-submit директива описує функцію обробник форми

Field Properties

  • $pristine  -  true, якщо форма не змінювалась
  • $valid – true, якщо поле форми або вся форма валідна

Field Properties & CSS

Bootstrap надає багато класів CSS для відображення стану валідації форми:

  • .has-error, .has-warning, .has-success
  • .help-block  - щоб відображати допоміжне повідомлення
<div class="col-lg-12 text-center">
	<h2 class="section-heading">Call Us</h2>
	<hr class="primary">
	<div class="row row-content">
	   <div class="col-xs-12">
		  <h3>Send us your Feedback</h3> 
	   </div>
		<div class="col-xs-12 col-sm-9" ng-controller="FeedbackController">
			<form class="form-horizontal" name="feedbackForm" ng-submit="sendFeedback()" novalidate>
				 <div class="form-group" ng-class="{ 'has-error' : feedbackForm.firstname.$error.required && !feedbackForm.firstname.$pristine }">
					<label for="firstname" class="col-sm-2 control-label">First Name</label>
					<div class="col-sm-10">
					<input type="text" class="form-control" id="firstname" name="firstname" placeholder="Enter First Name"
					ng-model="feedback.firstName" required>
					 <span ng-show="feedbackForm.firstname.$error.required && !feedbackForm.firstname.$pristine" class="help-block">Your First name is required.</span>
					</div>
				</div>
				<div class="form-group" ng-class="{ 'has-error' : feedbackForm.lastname.$error.required && !feedbackForm.lastname.$pristine }">
					<label for="lastname" class="col-sm-2 control-label">Last Name</label>
					<div class="col-sm-10">
						<input type="text" class="form-control" id="lastname" name="lastname" placeholder="Enter Last Name"
					ng-model="feedback.lastName" required>
					</div>
					<span ng-show="feedbackForm.lastname.$error.required && !feedbackForm.lastname.$pristine" class="help-block">Your Last name is required.</span>
				</div>
				<div class="form-group"  ng-class="{ 'has-error has-feedback' : feedbackForm.emailid.$invalid && !feedbackForm.emailid.$pristine }">
					<label for="emailid" class="col-sm-2 control-label">Email</label>
					<div class="col-sm-10">
						<input type="email" class="form-control" id="emailid" name="emailid" placeholder="Email"
						ng-model="feedback.email" required>
						<span ng-show="feedbackForm.emailid.$invalid && !feedbackForm.emailid.$pristine" class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>
					<span ng-show="(feedbackForm.emailid.$invalid ||
									feedbackForm.emailid.$error.required) &&
									!feedbackForm.emailid.$pristine"
						 class="help-block">Enter a valid email address.</span>
					</div>
				</div>
				<div class="form-group">
					<label for="telnum" class="col-sm-2 control-label">Subject</label>
					<div class="col-sm-10">
						<select class="form-control"
						   ng-model="feedback.mysubject"
						   ng-options="subject.value as subject.label for subject in subjects">
							<option value="">Your subject?</option>
						</select>
						<span ng-show="invalidSubjectSelection" class="help-block">Select an option.</span>
					</div>
				</div>
				<div class="form-group">
					<label for="feedback" class="col-sm-2 control-label">Your Feedback</label>
					<div class="col-sm-10">
						<textarea class="form-control" rows="12"
							ng-model="feedback.comments">
						</textarea>
					</div>
				</div> 
				<div class="form-group">
					<div class="col-sm-offset-2 col-sm-10">
						 <button type="submit" class="btn btn-primary" ng-disabled="feedbackForm.$invalid">Send Feedback</button>
					</div>
				</div>
			</form>
		</div>
		<div class="col-xs-12 col-sm-3">
		  <h3>Your Current Feedback:</h3>
		  <p>{{feedback.firstName}} {{feedback.lastName | uppercase }}</p>
		  <p>Contact Email: {{feedback.email}}</p>
		  <p>Subject: {{feedback.mysubject}}</p>
		  <p>Comments: {{feedback.comments}}</p>
		</div>
   </div>
</div>
<div class="col-lg-12 text-center">
	<h2 class="section-heading">Or</h2>
		<hr class="primary">
</div>
.controller('ContactController', ['$scope', function($scope) {

		$scope.feedback = {mysubject:"", firstName:"", lastName:"" , email:"", comments:""};
		
		$scope.subjects = [{value:"opinion", label:"Opinion"}, {value:"judgment",label:"Judgment"}, {value:"cooperation",label:"Сooperation"}, {value:"without",label:"Without subject"}];
		
		$scope.invalidSubjectSelection = false;
					
	}])

.controller('FeedbackController', ['$scope', function($scope) {
	
	$scope.sendFeedback = function() {
		
		console.log($scope.feedback);
		
		if ( $scope.feedback.mysubject == "" ) {
			$scope.invalidSubjectSelection = true;
			console.log('Select a subject!');
		}
		else {
			
			$scope.invalidSubjectSelection = false;
			$scope.feedback = {mysubject:"", firstName:"", lastName:"", email:"", comments:""};
			$scope.feedback.mysubject="";
			$scope.feedbackForm.$setPristine();
		}
	};
}])
<div class="well well-lg" ng-controller="NewBookController">
	<form class="form-horizontal" name="bookForm" ng-submit="sendBook()" novalidate>
		<div class="form-group" ng-class="{ 'has-error' : bookForm.bookName.$error.required && !bookForm.bookName.$pristine }">
			<label for="bookName" class="col-sm-2 control-label">Book Name</label>
			<div class="col-sm-10">
				<input type="text" class="form-control" id="bookName" name="bookName" placeholder="Enter Book Name" ng-model="newBook.name" required>
				<span ng-show="bookForm.bookName.$error.required && !bookForm.bookName.$pristine" class="help-block">Your Book name is required.</span>
			</div>
		</div>
		<div class="form-group" ng-class="{ 'has-error' : bookForm.bookLabel.$error.required && !bookForm.bookLabel.$pristine }">
			<label for="bookLabel" class="col-sm-2 control-label">Book Label</label>
			<div class="col-sm-10">
				<input type="text" class="form-control" id="bookLabel" name="bookLabel" placeholder="Enter Book Label" ng-model="newBook.label" required>
				<span ng-show="bookForm.bookLabel.$error.required && !bookForm.bookLabel.$pristine" class="help-block">Your Book label is required.</span>
			</div>
		</div>
		<div class="form-group" ng-class="{ 'has-error' : bookForm.bookPrice.$error.required && !bookForm.bookPrice.$pristine }">
			<label for="bookPrice" class="col-sm-2 control-label">Book Price</label>
			<div class="col-sm-10">
				<input type="text" class="form-control" id="bookPrice" name="bookPrice" placeholder="Enter Book Price" ng-model="newBook.price" required>
				<span ng-show="bookForm.bookPrice.$error.required && !bookForm.bookPrice.$pristine" class="help-block">Your Book price is required.</span>
			</div>
		</div>
		<div class="form-group">
			<label for="bookDescription" class="col-sm-2 control-label">Your Book description</label>
			<div class="col-sm-10">
				<textarea class="form-control" rows="12" ng-model="newBook.description">
				</textarea>
			</div>
		</div> 
		<div class="form-group">
			<div class="col-sm-offset-2 col-sm-10">
				 <button type="submit" class="btn btn-primary" ng-disabled="bookForm.$invalid">Add Book</button>
			</div>
		</div>
	</form>
</div>
.controller('NewBookController', ['$scope', function($scope) {
	
	$scope.newBook = {name : '', image : 'img/books/TheLordOfTheRings.jpg', 
            category : 'Books', label : '', price : '', description : ''};
	
	$scope.sendBook = function () {
		
		console.log($scope.newBook);
		
		$scope.books.push($scope.newBook);
		$scope.bookForm.$setPristine();
		$scope.newBook = {name : '', image : 'img/books/TheLordOfTheRings.jpg', 
                    category : 'Books', label : '', price : '', description : ''};
	}
}])

Angular Services

Вбудовані сервіси завжди починаються з $

  • $http , $scope, $rootScope, $location, $parse, $templateCache, $animate, $injector,…
  • Підключаються за допомогою  DI

Angular’s Built-in Services

  • Об'єкти пов'язані один з одним за допомогою DI
  •  Дозволяє організувати спільне використання коду в масштабах всього додатку
<script src="js/app/controllers/mainController.js"></script>
<script src="js/app/services/mainService.js"></script>

AngularJS: Scope. Forms validation. Factory, Service, Dependency Injection.

By Ievgen Liubarshchuk

AngularJS: Scope. Forms validation. Factory, Service, Dependency Injection.

AngularJS: Scope. Forms validation. Factory, Service, Dependency Injection.

  • 959
Loading comments...

More from Ievgen Liubarshchuk