问题
I tried in all ways (keeping the scope to false, etc but not able to change my scope in controller),am I missing something.
directive:
angular.module("ui.materialize.inputfield", [])
.directive('inputField', ["$timeout", function ($timeout) {
return {
transclude: true,
scope: {},
link: function (scope, element) {
$timeout(function () {
Materialize.updateTextFields();
// The "> > [selector]", is to restrict to only those tags that are direct children of the directive element. Otherwise we might hit to many elements with the selectors.
// Triggering autoresize of the textareas.
element.find("> > .materialize-textarea").each(function () {
var that = $(this);
that.addClass("materialize-textarea");
that.trigger("autoresize");
var model = that.attr("ng-model");
if (model) {
scope.$parent.$watch(model, function (a, b) {
if (a !== b) {
$timeout(function () {
that.trigger("autoresize");
});
}
});
}
});
// Adding char-counters.
element.find('> > .materialize-textarea, > > input').each(function (index, countable) {
countable = angular.element(countable);
if (!countable.siblings('span[class="character-counter"]').length) {
countable.characterCounter();
}
});
});
},
template: '<div ng-transclude class="input-field"></div>'
};
}]);
and here is my view
<div ng-controller="Example Controller"
<div input-field class="col l3">
<input type="text" ng-model="class1" length="150">
<label>Class</label>
{{class1}}
</div>
{{class1}}
</div>
I see that only class1 of the directive scope is changing but not the last class1,
if I initialize my controller with $scope.class1 = 9 only the first class1 is changing but not the second class1.Can any one help me regarding the problem
回答1:
The solution to your problem is to use controllerAs
syntax in your view.
<div ng-controller="ExampleController as ctrl"
<div input-field class="col l3">
<input type="text" ng-model="ctrl.class1" length="150">
<label>Class</label>
{{ ctrl.class1 }}
</div>
{{ ctrl.class1 }}
</div>
In your controller, instead of attaching properties to the $scope
, you attach it directly to your controller instance.
angular
.module('app')
.controller('ExampleController', function () {
var vm = this; // vm stands for View-Model and is reference to current controller instance
vm.class1 = 'some class';
});
This makes sure you are dealing with the same controller property class1
everywhere.
To understand why this works, read this documentation on how scope works in Angular
Understanding Scopes
回答2:
Your directive is working on the div it is set on, and the second class1 is outside of that div,and hence outside of the scope of your directive.
回答3:
never use primitve type model.always use with dot property.
change the ng-model from class to form1.class1
来源:https://stackoverflow.com/questions/38157691/scope-variable-not-changing-in-controller-when-changed-using-directive