I have build some kind of date picker with modal window. I have strange problems with the code. My scenario is like this, the user pick a range: start-date and end-date, then a pop up window is displayed. we displayed a variety of data which can be choose via radio box. The radio box is wired with ng-model:
<td><input class="dga_radio" type="radio" name="dga" value="{{$index}}" ng-model="selectedDga" />
</td>
apparently I suppose to get the index into selectedDga which is a scope variable.But what I see that no value is get inside that variable at all.
I am adding the entire code here:
The directive:
angular.module('directives', [])
.directive('datepicker', ['$timeout', 'dataFactory', function ($timeout, dataFactory) {
// Runs during compile
return {
scope: {
id: '#',
"class": '#',
onSelectStartDate: '&',
onSelectEndDate: '&',
onSelectGoMode: '&',
},
restrict: 'E',
templateUrl: 'Templates/datepicker.html',
replace: true,
link: function ($scope, iElm, iAttrs, controller) {
$scope.selectedDga;
var startDate, endDate;
$scope.selectStartDate = function (time) {
if (angular.isFunction($scope.onSelectStartDate())) {
$scope.onSelectStartDate()(time);
}
console.log('$scope.startDate', $scope.startDate);
}
$scope.selectEndDate = function (time) {
if (angular.isFunction($scope.onSelectEndDate())) {
$scope.onSelectEndDate()(time);
}
console.log('$scope.endDate', $scope.endDate);
}
//define blackout and close click callbacks.
$("#blackout, .close").click(function () {
$("#blackout").removeClass("visable");
$("#popup").removeClass("visable");
});
$("#GoBtn").click(function () {
if (angular.isFunction($scope.onSelectGoMode())) {
$scope.onSelectGoMode()();
}
var wmessage_container = $('#warning-message');
var wmessage = $('#warning-message > #wmessage');
startDate = $("#datepicker-start").val();
endDate = $("#datepicker-end").val();
console.log('reach here!');
if ((angular.isDefined(startDate) && startDate != '') && (angular.isDefined(endDate) && endDate != '')) {
console.log('case 1');
//check if startDate and endDate are valid
if (startDate > endDate) {
wmessage_container.show();
wmessage.text('start date and end date values are invalid!');
console.log('startDate is bigger than end date');
}
else {
var promise = dataFactory.getDGAList(startDate, endDate);
promise.then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
console.log('success callback');
console.log('response.status ', response.status);
console.log('response.data', response.data);
console.log('response.headers', response.headers);
console.log('response.config', response.config);
if (response.status == 200) {
$scope.collection = response.data;
}
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('promise callback');
console.log('response.data', response.data);
console.log('response.headers', response.headers);
console.log('response.config', response.config);
});
wmessage.text('');
wmessage_container.hide();
}
//call DataFactory service.
} else {
wmessage_container.show();
if ((startDate == '' || !angular.isDefined(startDate)) && (endDate == '' || !angular.isDefined(endDate)))
{
console.log('case 2');
wmessage.text('start date and end date are required !');
}
else if (startDate == '' || !angular.isDefined(startDate)) {
console.log('case 3');
wmessage.text('start date is required !');
} else {
console.log('case 4');
wmessage.text('end date is required !');
}
}
console.log('startDate', startDate);
console.log('endDate', endDate);
$("#blackout").addClass("visable");
$("#popup").addClass("visable");
});
var actions = [$scope.selectStartDate, $scope.selectEndDate];
$(".date-wrapper").each(function (index) {
console.log('directive index', index);
console.log('actions:', actions);
$input = $(this).find('input');
$btn = $(this).find('.calendar');
console.log('input', $input[0]);
console.log('btn', $btn[0]);
var counter = 0;
var updateTime = $scope.selectDate;
$input.attr('type', 'text');
var pickerStart = new Pikaday({
field: $input[0],
trigger: $btn[0],
container: $(this)[0],
format: 'DD/MM/YYYY',
firstDay: 1,
onSelect: actions[index]
});
$btn.show();
counter++;
});
}
};
}]);
The template:
<div id="{{id}}" class="{{class}}">
<div id="date-start-wrapper" class="date-wrapper">
<label for="datepicker-start" class="datepicker-lbl">From:</label>
<div class="fieldWrapper">
<input id="datepicker-start" type="date" placeholder="Select date" />
<a class="calendar"></a>
</div>
</div>
<div id="date-end-wrapper" class="date-wrapper">
<label for="datepicker-end" class="datepicker-lbl">To:</label>
<div class="fieldWrapper">
<input id="datepicker-end" type="date" placeholder="Select date" />
<a class="calendar"></a>
</div>
</div>
<button id="GoBtn" class="btn btn-primary btn-md">GO</button>
<div id="blackout"></div>
<div id="popup">
<span class="close"></span>
<div id="content">
<table cellpadding="10" cellspacing="10" border="1">
<tr>
<th></th>
<th>Id</th>
<th>Source</th>
<th>IsValid</th>
<th>Sampling Date</th>
</tr>
<tr ng-repeat="item in collection">
<td><input class="dga_radio" type="radio" name="dga" value="{{$index}}" ng-model="selectedDga" />
</td>
<td ng-repeat="(key,value) in item">
{{value}}
</td>
</tr>
</table>
selected_dga:{{selectedDga}}
</div>
<div id="warning-message">
<img src="../images/sign.png" width="32px" height="32px" />
<span id="wmessage" ></span>
</div>
<button id="okbtn" class="btn btn-success btn-md">ok</button>
<button id="cancelbtn" class="btn btn-danger btn-md">cancel</button>
</div>
</div>
If I am trying this in a simple directive then everything works like a charm, but in my current directive I don't get any value.
Calling the directive is something like this:
<datepicker id="thedatepicker" class="dates-wrapper" on-select-start-date="onSelectedStartDate" on-select-end-date="onSelectedEndDate" on-select-go-mode="Go" ></datepicker>
The answer is simple: I shouldn't use primitive in the ng-model.
Only adding exemple to #Brk answer:
It's just changing the primitive for an object. In my case:
In the controller:
$scope.name = 'Any Name' --> $scope.person = { 'name' : 'Any Name' };
In the directive:
ng-model="name" --> ng-model="person.name"
Simple like that!
Related
I am doing a table, with two filters checkbox. First is "360" - when you click it in table shows only 360, the same works filter "2D" - when you click it in table shows only 2D. I do this in JS, but what i want to do is when you click "360", in table shows only 360, but when you click "2D" at this time "360" is uncheck. I try to do this by radio button, but then my css checkbox don't works.
JSON "datas":
[{"type":"2D"},{"type":"2D"},{"type":"360"},{"type":"2D"},{"type":"360"},{"type":"2D"},{"type":"360"},{"type":"2D"},{"type":"360"},{"type":"2D"}]
My Html:
<div class="form-group" style="display:block;width:40px;padding-left: 5px;float:left;height:70px;">
<input type="checkbox" id='checkbox-360' class='tags-checkbox sr-only' value="" ng-model="type2.type360"><label for='checkbox-360'>
<i class='glyphicon glyphicon-unchecked' style="color:darkgrey;width:2px;font-size:25px;"></i>
<i class='glyphicon glyphicon-check' style="color:cornflowerblue;width:2px;font-size:25px;"></i>
<h4><small>360</small></h4>
</label>
</div>
<div class="form-group" style="display:block;width:40px;padding-left:5px;float:left;height:70px;">
<input type="checkbox" id='checkbox-20' class='tags-checkbox sr-only' value="" ng-model="type1.type2D"><label for='checkbox-20'>
<i class='glyphicon glyphicon-unchecked' style="color:darkgrey;width:2px;font-size:25px;"></i>
<i class='glyphicon glyphicon-check' style="color:cornflowerblue;width:2px;font-size:25px;"></i>
<h4><small>2D</small></h4>
</label>
</div>
<tr ng-repeat="data in datas |TypeFilter360:type2.type360 | TypeFilter2D:type1.type2D>
<td>{{data.type}}</td>
</tr>
CSS :
input[type='checkbox'].tags-checkbox:checked + label > i:first-of-type,
input[type='checkbox'].tags-checkbox + label > i:last-of-type{
display: none;
}
input[type='checkbox'].tags-checkbox:checked + label > i:last-of-type{
display: inline-block;
}
JS
var app = angular.module('app', []);
app.service('service', function($http, $q){
this.getDatas = function () {
var datas = $http.get('datas.json', {cache: false});
return $q.all({datas});
};
});
app.controller('FirstCtrl', function($scope, service, $http) {
var promise = service.getDatas();
promise.then(function (data) {
$scope.datas = data.datas.data;
console.log($scope.datas);
})
})
.filter('TypeFilter2D', function(){
return function(data, type2D){
if (!type2D) return data;
var filtered2D = [];
angular.forEach(data, function(item){
if(type2D == false) {
filtered2D.push(item);
}
else if(type2D == true && item.type == "2D"){
filtered2D.push(item);
}
});
return filtered2D;
};
})
.filter('TypeFilter360', function(){
return function(data, type360){
if (!type360) return data;
var filtered360 = [];
angular.forEach(data, function(item){
if(type360 == false) {
filtered360.push(item);
}
else if(type360 == true && item.type == "360"){
filtered360.push(item);
}
});
return filtered360;
};
})
Well what i want to do - when "360" filter is clicked, and then i click "2D" filter "360" should uncheck.
Thanks for answers in advance!
That behavior can actually be defined in your HTML using:
<input type="radio" name="filterOptions" id="checkbox-360" ... />
...
<input type="radio" name="filterOptions" id="checkbox-20" ... />
https://www.w3schools.com/tags/tag_input.asp
https://docs.angularjs.org/api/ng/input/input%5Bradio%5D
https://www.w3schools.com/html/tryit.asp?filename=tryhtml_radio
I am using the Bootstrap 3 Date/Time Picker (https://github.com/Eonasdan/bootstrap-datetimepicker) and I have problems
formatting the date
<input type="text" id="fmEndDate" class="form-control input-sm"
datetimepicker
format="DD-MM-YYYY hh:mm"
ng-model="workRequest.EndDate"
placeholder="..."
name="fmEndDate"
required
ng-disabled="isDisabled">
But the value is being display as MM/DD/YYYY hh:mm AM
i want 31-12-2017 23:59 for new year eve timestamp
This is my directive
"use strict";
angular.module("datetimepicker", [])
.provider("datetimepicker", function () {
var defaultOptions = { };
this.setOptions = function (options) {
defaultOptions = options;
};
this.$get = function () {
return {
getOptions: function () {
return defaultOptions;
}
};
};
})
.directive("datetimepicker", [
"$timeout",
"datetimepicker",
function ($timeout,datetimepicker) {
var defaultOptions = datetimepicker.getOptions();
return {
require : "?ngModel",
restrict: "AE",
scope : {
datetimepickerOptions: "#"
},
link : function ($scope, $element, $attrs, ngModelCtrl) {
var passedInOptions = $scope.$eval($attrs.datetimepickerOptions);
var options = jQuery.extend({}, defaultOptions, passedInOptions);
$element
.on("dp.change", function (e) {
if (ngModelCtrl) {
$timeout(function () {
ngModelCtrl.$setViewValue(e.target.value);
});
}
})
.datetimepicker(options);
function setPickerValue() {
var date = options.defaultDate || null;
if (ngModelCtrl && ngModelCtrl.$viewValue) {
date = ngModelCtrl.$viewValue;
}
$element
.data("DateTimePicker")
.date(date);
}
if (ngModelCtrl) {
ngModelCtrl.$render = function () {
setPickerValue();
};
}
setPickerValue();
}
};
}
]);
Any ideas?
As shown in the bootstrap3 docs you can define custom formats in JavaScript:
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker3'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('#datetimepicker3').datetimepicker({
format: 'your desired Formatting style'
});
});
</script>
</div>
</div>
Even more simple:
$("#fmEndDate").datetimepicker({format: 'dd-mm-yyyy hh:ii'});
Sidenote: Be careful with Date/Time formatting:
As for AngularJS HH format will result in hours as 00-23. While in Bootstrap3 which you are also using HH will result in hours as 01-12.
I highly suggest you to use a library like MomentJS which is doing the troublesome work for you.
Regards,
Megajin
I have angularjs app with a form that has a dropdownlist and and a datetimepicker.
When I change the dropdownlist I want to update the date displayed in the datepicker.
I get the following error when I change selected item in the dropdownlist
TypeError: Cannot read property 'apply' of undefined
at HTMLInputElement.<anonymous> (bootstrap-datetimepicker.min.js:2)
at Function.each (jquery-3.1.1.min.js:2)
at r.fn.init.each (jquery-3.1.1.min.js:2)
at r.fn.init.a.fn.datetimepicker (bootstrap-datetimepicker.min.js:2)
at m.$scope.SymbolChanged (moduleConfigformController.js:29)
at fn (eval at compile (angular.js:15197), <anonymous>:4:159)
at m.$eval (angular.js:18017)
at angular.js:25775
at Object.<anonymous> (angular.js:28600)
at q (angular.js:357)
This is the offending line of code:
$("#fmStartDate").datetimepicker("setDate", new Date($scope.simulationsettings.StartDate));
Here is my controller:
mainApp2.controller("moduleConfigformController",
function moduleConfigformController($scope, moduleConfigformService, $uibModalInstance) {
$scope.close = function (e) {
$uibModalInstance.dismiss();
e.stopPropagation();
};
$scope.formDebug = "loaded";
var settingsPromise = moduleConfigformService.simulationsettings();
settingsPromise.then(function (settings) {
$scope.simulationsettings = settings;
$scope.symbols = $scope.simulationsettings.symbols;
$scope.intervals = $scope.simulationsettings.intervals;
}).catch(function (error) {
throw error;
});
$scope.SymbolChanged = function () {
console.log("Symbol ddl changed");
console.log("New value is " + $scope.simulationsettings.Symbol);
// hardcoded date
// TODO: Find StartDate and EndDate where Symbol = $scope.simulationsettings.Symbol
$scope.simulationsettings.StartDate = "24/12/2014 8:26 PM";
// Display the new date in the datetimepicker
// This line produced the TypeError
$("#fmStartDate").datetimepicker("setDate", new Date($scope.simulationsettings.StartDate));
console.log("startdate is " + $scope.simulationsettings.StartDate);
console.log("startdate is " + $scope.simulationsettings.EndDate);
}
$scope.submitConfigForm = function () {
console.log("configform submitted");
var startDate = $scope.simulationsettings.StartDate;
var endDate = $scope.simulationsettings.EndDate;
var symbol = $scope.simulationsettings.Symbol;
var interval = $scope.simulationsettings.Intervals;
$scope.formDebug = "StartDate: " + startDate + " EndDate: " + endDate + " Symbol: " + symbol + " Interval: " + interval;
}
});
Here is my form:
<form name="configForm" ng-submit="submitConfigForm()">
<div class="modal-header" style="text-align:center">
<h3 class="modal-title">Configure</h3>
<div style="margin-top:10px">
<button tabindex="100" class="btn btn-success pull-left" type="submit" ng-class="{'btn-primary':configForm.$valid}">Start analysis</button>
<button class="btn btn-warning pull-right" ng-click="close($event)">Close</button>
</div>
</div>
<div class="modal-body">
<div class="col-sm-6" style="width: 100%;">
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-3">Symbol</label>
<div class="col-sm-9">
<select ng-model="simulationsettings.Symbol" ng-change="SymbolChanged()" name="fmSymbols" id="fmSymbols">
<option ng-repeat="item in symbols" value="{{item.Symbol}}">{{item.Symbol}}</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">start date</label>
<div class="col-sm-9">
<input type="text" id="fmStartDate" class="form-control input-sm"
datetimepicker
ng-model="simulationsettings.StartDate"
placeholder="..."
name="fmStartDate">
</div>
</div>
</div>
form debug: '{{formDebug}}'
</div>
</div>
The datetimepicker directive
"use strict";
angular.module("datetimepicker", [])
.provider("datetimepicker", function () {
var defaultOptions = {};
this.setOptions = function (options) {
defaultOptions = options;
};
this.$get = function () {
return {
getOptions: function () {
return defaultOptions;
}
};
};
})
.directive("datetimepicker", [
"$timeout",
"datetimepicker",
function ($timeout,datetimepicker) {
var defaultOptions = datetimepicker.getOptions();
return {
require : "?ngModel",
restrict: "AE",
scope : {
datetimepickerOptions: "#"
},
link : function ($scope, $element, $attrs, ngModelCtrl) {
var passedInOptions = $scope.$eval($attrs.datetimepickerOptions);
var options = jQuery.extend({}, defaultOptions, passedInOptions);
$element
.on("dp.change", function (e) {
if (ngModelCtrl) {
$timeout(function () {
ngModelCtrl.$setViewValue(e.target.value);
});
}
})
.datetimepicker(options);
function setPickerValue() {
var date = options.defaultDate || null;
if (ngModelCtrl && ngModelCtrl.$viewValue) {
date = ngModelCtrl.$viewValue;
}
$element
.data("DateTimePicker")
.date(date);
}
if (ngModelCtrl) {
ngModelCtrl.$render = function () {
setPickerValue();
};
}
setPickerValue();
}
};
}
]);
Any idea how to update the datetimepicker so it displays the updated value?
You are updating the model here:
$scope.simulationsettings.StartDate = "24/12/2014 8:26 PM";
Then you try to set the datepickers value here:
$("#fmStartDate").datetimepicker("setDate", new Date($scope.simulationsettings.StartDate));
But the datepicker has $scope.simulationsettings.StartDate as model. This is why you get the error. Angular is trying to call the digest cycle twice.
Your function should look like this:
$scope.SymbolChanged = function () {
console.log("Symbol ddl changed");
console.log("New value is " + $scope.simulationsettings.Symbol);
// hardcoded date
// TODO: Find StartDate and EndDate where Symbol = $scope.simulationsettings.Symbol
// the binding should be of the same type as your input, it means that the value returned from the datepicker must be a Date
$scope.simulationsettings.StartDate = new Date("24/12/2014 8:26 PM");
// This line is useless, the datepicked model is binded to $scope.simulationsettings.StartDate
// $("#fmStartDate").datetimepicker("setDate", new Date($scope.simulationsettings.StartDate));
console.log("startdate is " + $scope.simulationsettings.StartDate);
console.log("startdate is " + $scope.simulationsettings.EndDate);
}
But since you are using an input type="text" we need more information on the datetimepicker directive that you are using.
your are trying to put a date object in text field which may work if you're not using a date-picker
1/ change your input type to type date or change this $("#fmStartDate").datetimepicker("setDate", new Date($scope.simulationsettings.StartDate));
to this $("#fmStartDate").datetimepicker("setDate", $scope.simulationsettings.StartDate);
and it may work if your date-picker accepts this format "24/12/2014 8:26 PM"
2/ you may wanna check the date-picker documentation for the accepted format types
I am using angular js,My target is to show a html table on (enter of spacebar) in textbox and add the element of the table in that textbox,for that i have written a directive,but i am not sure whether i have done it in right path..Ohk i will show it in detail to be more clear
Here is my html textbox
<input type="text" helps ng-model="firstText" code="1">
<div class="col-xs-4 pull-right" helps donotapply=true></div> //Do i need this??
Here helps is my directive which binds my html to the div,here is my directive code
app.directive('helps', ['$parse', '$http','$filter', function ($parse, $http,$filter) {
return {
restrict: 'AE',
scope: true,
templateUrl: 'Table.html',
link: function (scope, element, attr) {
console.log(element);
element.bind("keypress", function (event) {
if (event.which === 114 || event.which === 32) {
scope.enterMe = function () { // this is to add data to Table
scope.newArray = [
{'code' :1,'name' : 'name1','age' : 24},
{'code' : 2,'name' : 'name2','age' : 26},
{'code' : 3,'name' : 'name3','age' : 25}
]
};
scope.setElement = function (element) { // Here set element function is to add my table name to textbox
var modelValue = tempattr.ngModel + '_value';
var model = $parse(tempattr.ngModel);
model.assign(scope, element.name);
modelValue = tempattr.ngModel + '_value';
modelValue = $parse(modelValue);
modelValue.assign(scope, element.code);
};
}
}
});
}
}
}]);
And Now here my Table.html
<div class="col-xs-4 pull-right" ng-show="hideMyMtHelpDiv">
<input type="text" ng-model="searchText" placeholder="search">
<input type="button" ng-model="gad" value="GO" ng-click="enterMe();">
<table ng-show="getTableValue" class="table table-bordered table-responsive table-hover add-lineheight table_scroll">
<thead>
<tr>
<td>
Code
</td>
<td>
Name
</td>
<td>
Age
</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="test in newArray" ng-dblclick="setElement(test);">
<td>
{{test.code}}
</td>
<td>
{{test.name}}
</td>
<td>
{{test.age}}
</td>
</tr>
</tbody>
</table>
</div>
Now my question is that, my table is binded with my div as well as my input textbox; So, is there any proper way to do this?
If my question is still unclear kindly comment.
Thank you for any help
Check my plunker here https://plnkr.co/edit/lAUyvYKp1weg69CsC2lg?p=preview
and read README
First of all you are using the save directive in both input and div. You can separate those as first step:
mod.directive('onKeydown', function() {
return {
restrict: 'A',
scope: {
setShowSearch: '&'
},
link: function(scope, elem, attrs) {
elem.on('keydown', function(event){
if (event.which === 114 || event.which === 32) {
setShowSearch()(true);
}
});
}
};
});
Then you can pass a function to set your showSearch variable to that directive and use that on your input:
<input type="text" ng-model="firstText" hpcode="1" on-keydown="" set-show-search="setShowSearch"/>
Now that setShowSearch is living in your controller not your directive so it has its own scope.
myApp.controller('MyController', ['$scope', function($scope) {
$scope.setShowSearch = function(show) {
//do whatever you want here
};
$scope.msg = 'This Must Work!';
}]);
Once done you now have a clean directive which is responsible for showing the table and the rest is just passing that array down to that directive in a similar way.
Hope this helps.
I am using in my application angular.js and html. So, I would like to autocomplete a textbox,but only when the length of the field "UserSearch" is greater than 3.
MY HTML
<div class="col-sm-8">
<div class="input-group">
<input data-ng-model="UserSearch" ng-change="selectSearchType(UserSearch)" list="title" type="text" class="form-control" placeholder="Name to search">
<span class="input-group-btn">
<button class="btn btn-primary" type="button"><i class="glyphicon glyphicon-search"></i></button>
</span>
<datalist id="{{test}}">
<option data-ng-repeat=" user in AllUser" value="{{user.name}}">
</datalist>
</div>
</div>
MY JS
$scope.test = "";
$scope.selectSearchType = function (UserSearch) {
if (UserSearch.length > 3) {
$scope.test = "title";
$http.get("/api/getAllUser?SearchUser=" + UserSearch).success(function (data) {
$scope.AllUser = data;
})
}
else {
$scope.test = "";
}
}
I still have the same problem.. When i type a name in the field, two names appears in the datalist, but when I click on the triangle on the top of the texbox, all data appears... What can I do to fix this problem ?
If you're using the HTML5 datalist, then in essence you're rolling your own autocomplete.
What I would recommend, is to create a directive that encapsulates your above code.
So this:
<div class="input-group">
<input data-ng-model="UserSearch" ng-change="selectSearchType(UserSearch)" list="title" type="text" class="form-control" placeholder="Name to search">
<span class="input-group-btn">
<button class="btn btn-primary" type="button"><i class="glyphicon glyphicon-search"></i></button>
</span>
<datalist id="{{test}}">
<option data-ng-repeat=" user in AllUser" value="{{user.name}}">
</datalist>
</div>
Turns into this:
<autocomplete
search="UserSearch"
on-select="selectSearchType"
min-search="3"
list="user in AllUser">
</autocomplete>
The basic directive looks like this:
var app = // get your angular module
app.directive('autocomplete', function () {
return {
replace: true,
restrict: 'E',
scope: {
search: "=",
minSearch: "=",
list: "=",
onSelect: "="
},
templateUrl: 'template/autocomplete-template.html', // use the above template
link: function (scope, el, attrs) {
scope.$watch('UserSearch', function() {
if(scope.search.length > scope.minSearch) {
// this onSelect function will callback
// into your controller
scope.onSelect(search);
}
});
}
}
});
You can now call into your controller to make your AJAX call. This callback will allow you to use the component in different places in your project.
As #Rich comments, it's not certain what the problem seems to be. However, check this fiddle. It uses $scope.$watch to watch for changes in UserSearch, firing a request through $http if the text is longer than 3 characters.
$scope.$watch('UserSearch', function(UserSearch) {
if (UserSearch && UserSearch.length > 3) {
$http.get('/api/getAllUser?SearchUser=' + UserSearch).success(function(users) {
$scope.AllUser = users;
}).error(function() {
$scope.AllUser = [{name: 'test'}, {name: 'example'}];
});
}
});