bullgare
bullgare

Reputation: 1773

Setting initial values and trigger click on application init in angularjs

I'm stuck with this.

I have a search page that is using html5 history api.

So if I search for "html5", my url is "/search/html5".

Now I want my application to handle page refresh. When I press "F5" I want to see my application to fill text input with "html5" and trigger click on button to start search method.

    <form>
        <input type="text" ng-model="searchText" />
        <button class="btn btn-primary" ng-disabled="!searchText" ng-click="search()" >search</button>
    </form>

I would really appreciate some help with it.

UPD: I mean I need to do manually (outside of angular's controllers) something like

$scope.searchText = 'html5';
$scope.search();

But I can not get how can I have access to $scope.

Upvotes: 2

Views: 3361

Answers (3)

bullgare
bullgare

Reputation: 1773

There's another good solution for that.

I like it becase it's native and doesn't need any 3rd party library.

Just add this in somewhere in your html (again, I'm using ejs for the server templating):

<p ng-init="searchText = '<%= searchText %>'; search();"></p>

This way is better than that https://stackoverflow.com/a/13232922/801426 because while using latter input's value doesn't update until the search is finished, and it's an ajax call so it takes some time.

Upvotes: 4

bullgare
bullgare

Reputation: 1773

I found solution for that (I'm using ejs for the server templating):

<script type="text/javascript">
    (function( $ )
    {
        "use strict";
        $(document).ready(function (){
            var $scope = angular.element($('#search-text')).scope();
            $scope.searchText = "<%= searchText %>";
            $scope.search();
        });
    }( jQuery ));
</script>

Thanks to that question - Call Angular JS from legacy code

Upvotes: 1

Tosh
Tosh

Reputation: 36030

http://plnkr.co/edit/VT5ss4

This can be one way to do it. It is using angular's routing feature. $routeParams will provides you the way to access the searchText in this case.

Upvotes: 1

Related Questions