JSFiddle - React, Tailwind, and code Playground
by dameleon
HTML
<div ng-app="sample">
<dl>
<dt>基本</dt>
<dd>
<div ng-controller="HogeController">
<sample-false></sample-false>
<sample-true></sample-true>
<sample-object foo="foo" func="func()"></sample-object>
</div>
</dd>
<dt>true の場合に同一 $scope 以下の各ディレクティブで値が共有される</dt>
<dd>
<div ng-controller="HogeController">
<!-- 確認のために2つ置く -->
<sample-true-scope-instance></sample-true-scope-instance>
<sample-true-scope-instance></sample-true-scope-instance>
</div>
<div ng-controller="FugaController">
<!-- 確認のために2つ置く -->
<sample-true-scope-instance></sample-true-scope-instance>
<sample-true-scope-instance></sample-true-scope-instance>
</div>
</dd>
</dl>
</div>
JavaScript
var module = angular.module('sample', []);
module.controller('HogeController', function ($scope) {
$scope.count = 0;
$scope.foo = 'hoge';
$scope.func = function () {
console.log('Called ' + $scope.foo);
};
$scope.add = function() {
$scope.count++;
};
});
module.controller('FugaController', function ($scope) {
$scope.count = 0;
$scope.foo = 'fuga';
$scope.func = function () {
console.log('Called ' + $scope.foo);
};
$scope.add = function() {
$scope.count++;
};
});
// 基本用のテンプレ
// ボタンをクリックした時に console.log で $scope.foo を出力する
// ボタン内は foo, fooInnerBind を表示する
var template = '<button ng-click="func()">{{ foo }}{{ fooInnerBind }}</button>';
// false を指定(デフォルト)
module.directive('sampleFalse', function () {
return {
restrict: 'E',
template: template,
scope: false
};
});
// true を指定
module.directive('sampleTrue', function () {
return {
restrict: 'E',
template: template,
scope: true
};
});
// Object を指定
module.directive('sampleObject', function () {
return {
restrict: 'E',
template: template,
scope: {
// '{$scope 内で展開する key 名}' : '{親の値との関連づけ式}' のように指定していく
// アトリビュートの key 名とディレクティブの $scope へ展開する key 名が同一の場合は、関連づけ式の後ろの指定を省略できる
// アトリビュートの値を参照し、データを取る
// directive[foo="foo"] の場合はアトリビュート値が直接使用されるが
// directive[foo="{{ foo }}"] となっている場合は親の $scope からデータバインディングされる
// 表記の仕方は右記と等価 -> foo: '@foo'
foo: '@',
// アトリビュートの値から親の $scope を参照し、データを取る
// directive[foo="foo"] であれば、親 $scope の foo 値を参照する
// つまり directive[foo="{{ foo }}"] かつ foo: '@foo' と指定した場合と同一の挙動になる
fooInnerBind: '=foo',
func: '&'
}
};
});
// true を指定($scope のインスタンス比較用)
module.directive('sampleTrueScopeInstance', function () {
return {
restrict: 'E',
//...