因此,我的目标是对一系列活动进行 ng-repeat,并根据活动类型显示特定指令。现在,我只是在测试这个想法,看看它是否可行。我可以动态显示指令,但关键是我希望在 main.js 中的活动和显示的指令之间有两种方式绑定。
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
}];
}]);
});
动态指令.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));
}
};
}
]);
});
活动1.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: '='
}
};
}
]);
});
活动1.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>
按照现在的设置方式,console.log 输出 $scope.instance 未定义。因此,$scope.thisInstance.isIncluded 默认为 false。如果在 main.html 中,我设置attributes="instance='{{activities[0]}}'"
了 $scope.thisInstance.isIncluded 正确设置为 true,但我没有双向绑定,而不是作为本质上的指针传递的活动 [0],它传递了值, { type: "activity1", isIncluded: true }。我怎样才能让双向绑定工作?可能吗?有一个更好的方法吗?