So, my goal is to ng-repeat over an array of activities and display a specific directive based off of the activity type. Right now, I'm just testing the idea out to see if it is viable. I can display a directive dynamically, but the key is I want to have two way binding between the activities in the main.js and the directive that is displayed.
main.html
<div ng-controller="mainCntrl">
<div>Activity: { <div>isIncluded: {{activities[0].isIncluded}}</div> }</div>
<dynamic-directive type="{{activities[0].type}}" attributes="instance='activities[0]'"></dynamic-directive>
</div>
main.js
define(['angularAMD', 'dynamicDirective', 'activity1'],
function (angularAMD) {
'use strict';
var app = angular.module('mainModule', []);
app.controller('mainCntrl', ['$rootScope', '$scope',
function ($rootScope, $scope) {
$scope.activities = [{
type: "activity1",
isIncluded: true
}];
}]);
});
dynamicDirective.js
define('dynamicDirectiveModule', ['angularAMD'], function (angularAMD) {
'use strict';
var app = angular.module('dynamicDirectiveModule', []);
app.directive('dynamicDirective', ['$compile',
function ($compile) {
return {
restrict: 'E',
scope: {
type: '@',
attributes: '@'
},
link: function (scope, element) {
var generatedDirective = '<' + scope.type + ' ' + scope.attributes + '></' + scope.type + '>';
element.append($compile(generatedDirective)(scope));
}
};
}
]);
});
activity1.js
define('activity1Module', ['angularAMD'], function (angularAMD) {
'use strict';
var app = angular.module('activity1Module', []);
app.controller('activity1Cntrl', ['$scope',
function ($scope) {
console.log("$scope.instance: " + $scope.instance);
$scope.thisInstance = $scope.instance || {};
}
]);
app.directive('activity1', [
function () {
return {
restrict: 'E',
templateUrl: 'processes/templates/Activity1',
controller: 'activity1Cntrl',
scope: {
instance: '='
}
};
}
]);
});
activity1.html
<div>
<div>ISINCLUDED: {{thisInstance.isIncluded}}</div>
<button ng-model="thisInstance.isIncluded" value="true">Yes</button>
<button ng-model="thisInstance.isIncluded" value="false">No</button>
</div>
With the way it is set up now, the console.log outputs that $scope.instance is undefined. So, $scope.thisInstance.isIncluded defaults to false. If, in the main.html, I set attributes="instance='{{activities[0]}}'"
, $scope.thisInstance.isIncluded correctly is set to true, but I have no two-way binding as instead of activities[0] being passed in as essentially a pointer, it passes the value, { type: "activity1", isIncluded: true }. How can I get the two-way binding to work? Is it possible? Is there a better way to do this?