var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.onChange = function () {
console.log('name is changed!');
};
$scope.onChange2 = function () {
console.log('name is changed!!');
}
$scope.onChange3 = function () {
console.log('name is changed!!!');
}
});
app.directive('hoge', function ($compile) {
var template = '<label>{{label}}</label><input ng-model="model" type="text">';
return {
restrict: 'E',
replace: true,
require: '?ngModel',
template: '<div></div>',
link: function (scope, element, attrs, ngModelCtrl) {
var child = scope.$new();
element.append($compile(template)(child));
attrs.$observe('label', function() {
child.label = attrs.label;
});
// parent -> child
scope.$watch(attrs.ngModel, function (value) {
child.model = value;
});
// child -> parent
child.$watch('model', function (value) {
ngModelCtrl.$setViewValue(value);
});
}
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.2.x" src="http://code.angularjs.org/1.2.3/angular.js" data-semver="1.2.3"></script>
<script src="app.js"></script>
</head>
<body ng-app="plunker">
<div ng-controller="MainCtrl">
<input ng-model="name" ng-change="onChange()">
<p>Hello {{name}}!</p>
<hoge ng-model="name" label="{{name}}" ng-change="onChange2()"></hoge>
<hoge ng-model="name" label="Bar" ng-change="onChange3()"></hoge>
</div>
</body>
</html>
/* Put your css in here */