Pass Directive Isolate Scope Bindings To Its Controller `this` Context (angularjs V1.6)
Solution 1:
Set the bindToController property to true
.directive('directive', [ function () {
return {
restrict: 'AE',
scope: {
value: '=value'
},
//USE bindToControllerbindToController: true,
templateUrl: 'item.html',
controller: 'Item as item'
};
}])
bindToController
This property is used to bind scope properties directly to the controller. It can be either
true
or an object hash with the same format as the scope property.When an isolate scope is used for a directive (see above),
bindToController: true
will allow a component to have its properties bound to the controller, rather than to scope.After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller properties. You can access these bindings once they have been initialized by providing a controller method called
$onInit
, which is called after all the controllers on an element have been constructed and had their bindings initialized.
Use the $onInit
life-cycle hook
.controller('Item', functionItem () {
this.$onInit = function() {
console.log(this.value);
};
})
$compile
:Due to bcd0d4, pre-assigning bindings on controller instances is disabled by default. It is still possible to turn it back on, which should help during the migration. Pre-assigning bindings has been deprecated and will be removed in a future version, so we strongly recommend migrating your applications to not rely on it as soon as possible.
Initialization logic that relies on bindings being present should be put in the controller's
$onInit()
method, which is guaranteed to always be called after the bindings have been assigned.
Solution 2:
It should be on your directive's scope
, and you can access it inside the link
method like so:
app.directive('directive', function () {
return {
restrict: 'AE',
scope: {
value: '='
},
templateUrl: 'item.html',
link: function (scope, element, attrs) {
console.log(scope.value);
}
};
});
Post a Comment for "Pass Directive Isolate Scope Bindings To Its Controller `this` Context (angularjs V1.6)"