I'm in the process of upgrading from AngularJS 1.4.x to 1.7.x. The app has a lot of Directives with pre-assigned bindings (which are a no-go in 1.7.x). I'm looking for the best way to migrate with minimal changes.
Current code example:
angular.module('app')
.directive('logo', ['ENV', 'utils',
function main(ENV, utils) {
return {
template: '<div><img></div>',
restrict: 'E',
replace: true,
scope: {
height: '@',
imgClass: '@',
imgStyle: '@',
abbr: '@',
width: '@',
abbrObj: '=',
url: '='
},
link: function postLink(scope, element) {
if (scope.abbr) scope.abbrObj = utils.getObjByAbbr(scope.abbr);
...
This obviously throws an error:
Error: [$compile:nonassign] Expression 'undefined' in attribute 'abbrObj' used with directive 'logo' is non-assignable!
I've tried the following:
scope: {
height: '@',
imgClass: '@',
imgStyle: '@',
abbr: '@',
width: '@',
abbrObj: '=',
url: '='
},
controller: function controller() {
// Initialize
this.$onInit = function onInit() {
console.log(this.abbrObj, this.abbr); // results in undefined, undefined
if (this.abbr) this.abbrObj = utils.getObjByAbbr(this.abbr);
};
},
link: function postLink(scope, element) {
...
I don't understand why the console in the Controller is returning undefined.
I've also tried using bindToController: true
but then the postLink function can't see the updated properties as it only has access to the scope
.
What's the best way to use $onInit
with minimal changes?