Yii2 Case Study (1) : Angular JS
This is an example how to combine Yii2 with AngularJS. We have one table, game. 1. Table Preparation Table game : Create model Game.php using Gii, put it in common\models folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<?php namespace common\models; use Yii; /** * This is the model class for table "game". * * @property integer $id * @property string $console * @property string $name * @property string $year */ class Game extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'game'; } /** * @inheritdoc */ public function rules() { return [ [['console', 'name'], 'string', 'max' => 255], [['year'], 'string', 'max' => 11], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app', 'ID'), 'console' => Yii::t('app', 'Console'), 'name' => Yii::t('app', 'Name'), 'year' => Yii::t('app', 'Year'), ]; } } |
2. Create GameController.php, index.php, app.js and Use AngularJS 1.6 create frontend/controllers/GameController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php namespace frontend\controllers; use Yii; use yii\web\Controller; use common\models\Game; class GameController extends Controller{ public function beforeAction($action){ $this->enableCsrfValidation = false; return parent::beforeAction($action); } public function actionIndex(){ return $this->render('index'); } } |
create frontend/views/game/index.php Use AngularJS 1.6, and put https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js inside this file.
1 2 3 4 5 6 7 8 |
<div ng-app="App" ng-controller="AppCtrl"> <h4>{{6+4}}</h4> </div> <?php echo $this->registerJsFile("https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"); echo $this->registerJsFile("js/app.js"); ?> |