Reputation: 163
I am new to AngularJS I have two programs written. First is auto appending input text box
<div ng-app="myApp" ng-controller="MyCtrl">
[<span ng-repeat="input in inputs">"{{input.field}}"</span>]
<div ng-repeat="input in inputs">
<label>{{$index+1}}</label>
<input type="text" ng-model="input.field" capitalize-first>
<button ng-click="removeInput($index)">-</button>
</div>
<button ng-click="addInput()">+</button>
</div>
------------------------------------------------------------
var app = angular.module('myApp', []);
app.controller('MyCtrl', ['$scope', function ($scope) {
$scope.inputs = [];
$scope.addInput = function(){
$scope.inputs.push({field:''});
}
$scope.removeInput = function(index){
$scope.inputs.splice(index,1);
}
}]);
http://jsfiddle.net/A6G5r/134/
and second is Auto capitalization Filter using directive.
<div ng-controller="MyCtrl">
<input type="text" ng-model="input.field" capitalize-first>
</div>
var myApp = angular.module('myApp',[]);
myApp.directive('capitalizeFirst', function(uppercaseFilter, $parse) {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
var capitalize = function(inputValue) {
var capitalized = inputValue.charAt(0).toUpperCase() +
inputValue.substring(1);
if(capitalized !== inputValue) {
modelCtrl.$setViewValue(capitalized);
modelCtrl.$render();
}
return capitalized;
}
var model = $parse(attrs.ngModel);
modelCtrl.$parsers.push(capitalize);
capitalize(model(scope));
}
};
});
function MyCtrl($scope) {
$scope.name = '';
}
http://jsfiddle.net/YyYnM/339/
First is written using controller and another uses directive. I am not able to merge two programs and cannot understand scope of directive and controller while merging.
Can anyone suggest me how would be proper way while merging these two ?
Upvotes: 0
Views: 180
Reputation: 22323
Don't declare modules in this way. Using a variable for module assignment isn't necessary, and creates a leaky abstraction.
Instead, you should use the module getter and setter syntax. See this excerpt from John Papa's Style Guide for more information on this and other best practices.
Instead of:
var app = angular.module('myApp', []);
app.controller('MyCtrl', ['$scope', function ($scope) {
use:
angular.module('myApp', []);
angular.module('myApp').controller('MyCtrl', ['$scope', function ($scope) {
Then, in the second file (directive), you don't need to declare the myApp
module again, merely chain onto the declaration:
angular.module('myApp').directive('capitalizeFirst', function(uppercaseFilter, $parse) {
Upvotes: 1