Search code examples
jqueryangularjsjquery-templates

Angular to fire on TextBox change


I'm new to Angular and trying to figure this out. There may even be a better way to do this than what I'm doing. I'm open to suggestions.

I have a text box that I want to use to call a service "onChange".

I have a results section that will get updated. This section uses a template.

What I'm trying to do is combine the use of js templates with Angular for code clarity and other reasons.

The code I'm using (below) is producing an error that looks something like:

Error: [$compile:ctreq] http://errors.angularjs.org/1.3.16/$compile/ctreq?p0=ngModel&p1=ngChange... etc.

Here's the main HTML section:

<div ng-controller="SLTSearchController">
    <input id="searchInput" type="text" ng-change="change()" ng-model="searchInput" />
</div>
<div id="listContent"></div>

Here's the HTML template:

<script id="brand-template" type="application/html-template">
    <div id="listContent" ng-controller="SLTSearchController">
        <div class="radioForm" ng-repeat="item in BrandNames">
            <div id="tier-checkCont-{{item.BrandId}}" ng-controller="SLTSearchController">
                <input name="{{item.BrandName}}" id="brand-{{item.BrandId}}" type="radio" value="{{item.BrandName}}" />
                <label id="tier-label-{{item.BrandId}}" for="{{item.BrandName}}">
                        {{item.BrandName}}
                </label>
             </div>
         </div>
     </div>
</script>

Here's the JS:

var sltApp = angular.module('sltApp', []);

sltApp.controller('SLTSearchController', ['$scope', '$http', function ($scope, $http) {
    //$scope.searchInput //not sure what to do with this, if anything
    $scope.change = function () {
        $http.get('[link to web service]').
                success(function (data) {
                    alert('success');
                    $scope.BrandNames = data;
                    doresultswindowreplace();
                }).
                error(function () {
                    alert('fail');
                });
    };
}]);
    function doresultswindowreplace() {
        var resultstemplate = $('#brand-template').clone().html();

        $('#listContent').replaceWith(resultstemplate);
    }

Solution

  • You have to set the ng-model in your input in order to use ng-change, if it's not defined you get that error. I use a variable name just as example.

    <input id="searchInput" type="text" ng-change="change()" ng-model="name"/>