Updated with three methods that work, and an original one that doesn't
I created an angular js directive and I'm trying to access ctrl.$modelValue. It does not work in the main thread.
I have three potential solutions, all of which have flaws.
Method 1 does not work, as I hope, and I cannot find any other property available in the directive directly accessible in this way.
Method 2 works because it waits until the current thread completes and then executes at the next moment. This happens after the completion of the angular js life cycle, and at the moment the controller seems to be connected to the model. For me, this does not seem ideal, since he is waiting for the completion of the entire performance. If possible, I would prefer to run my code as soon as the controller is connected to the model, and not after the code has completed in the current thread.
Method 3 works well, accessing the model from $scopeand determining that the model from the string representation refers to the object attrs. The downside is that this method uses eval to get the address value - and, as we all know, eval is evil.
4 , . , , , while loop. , 100% . , , for.
, 5- , ?
HTML:
<div ng-app="myApp">
<div ng-controller="inControl">
I like to drink {{drink.type}}<br>
<input my-dir ng-model="drink.type"></input>
</div>
</div>
JavaScript:
var app = angular.module('myApp', []);
app.controller('inControl', function($scope) {
$scope.drink = {type:'water'};
});
app.directive('myDir', function(){
return {
restrict: 'A',
require: 'ngModel',
link: function($scope, element, attrs, ctrl) {
console.log({"method-1": ctrl.$modelValue});
setTimeout(function(){
console.log({"method-2": ctrl.$modelValue});
},0);
console.log({"method-3": eval("$scope."+attrs.ngModel)});
var getProperty = function(obj, prop) {
var parts = prop.split('.'),
last = parts.pop(),
l = parts.length,
i = 1,
current = parts[0];
while((obj = obj[current]) && i < l) {
current = parts[i];
i++;
}
if(obj) {
return obj[last];
}
}
console.log({"method-4": getProperty($scope,attrs.ngModel)});
}
};
});