JSFiddle - React, Tailwind, and code Playground
by Chris Bao
HTML
<div ng-app="app">
<div ng-controller="ParentCtrl as parent">
<foo-directive all-data="parent.sourcedata" city-data="parent.cityList"></foo-directive>
</div>
</div>
CSS
</style>
<script src="//code.angularjs.org/1.6.2/angular.min.js"></script>
<style>
JavaScript
function ParentCtrl($timeout){
//this.cityList= ["London","New York"];
$timeout(function(){
this.sourcedata = [
{
cityname:"London",
restaurantList:["KFC1","KFC2","KFC3"]
},
{
cityname:"New York",
restaurantList:["Moc1","Moc2","Moc3"]
}
];
this.cityList= ["London","New York"];
}.bind(this),2000);
}
function FirstCtrl() {
this.name = 'First Controller';
this.$onInit = function(){
this.show = function(){
console.log(this);
}
this.getRestList = function(cityname){
for(var i = 0 ; i< this.allData.length; i++){
if (this.allData[i].cityname === cityname){
var result = this.allData[i].restaurantList;
break;
}
}
this.restList = result;
}
}
}
function fooDirective() {
return {
scope: {
allData: '=',
cityData : '='
},
controller: 'FirstCtrl',
controllerAs: 'foo',
bindToController: true,
template:
'<div ng-repeat="eachcity in foo.cityData" ng-bind="eachcity" ng-click="foo.getRestList(eachcity)"></div>' +
'<ul><li ng-repeat="eachrest in foo.restList" ng-bind="eachrest"></li></ul>'
,
link: function ($scope, $element, $attrs, $ctrl) {
//console.log($ctrl.name);
$scope.$watch('foo.cityData',function(newvalue,oldvalue){
console.log("debugging watching...")
if (newvalue === oldvalue ){
return;
}
console.log("data loaded")
$ctrl.getRestList($scope.foo.cityData[0]);
})
}
};
}
angular
.module('app', [])
.directive('fooDirective', fooDirective)
.controller('FirstCtrl', FirstCtrl)
.controller('ParentCtrl',ParentCtrl)