Stéphane de Luca
Stéphane de Luca

Reputation: 13603

Binding an input and make the model persistant throughout the app in angularjs

Just want to enable a user to make searches from several points throughout the app screens.

How to persist the model?

The HTML for the search is as follows:

        <input 
            style="width:80%"
            ng-model="searchKeyword"
            id="search" 
            size="70" 
            type="search" 
            results="5" 
            placeholder="symptôme, maladie, etc." 
        />

This code snippet is located at several locations, including some partials. Currently, it sounds like the value entered in one of these does not persist in all forms.

[EDIT] searchKeyword belongs to the controller scope.

[EDIT 2] Here is a fiddle that demonstrate the issue I want to fix in the very context it takes place in my app: http://jsfiddle.net/stephanedeluca/abHFQ/

Any idea?

Upvotes: 0

Views: 199

Answers (1)

artur grzesiak
artur grzesiak

Reputation: 20348

You can use custom directive. DEMO-UPDATED

Seed of js code:

app.directive("search", function(){

  var search = {
    keyword : ""
  }

  return {

    restrict : "EA",

    scope: {},

    template : '<input \
            style="width:80%" \
            ng-model="search.keyword" \
            size="70" \
            type="search" \
            results="5" \
            placeholder="symptôme, maladie, etc." \
        />',

    link : function(scope, element, attrs){
      scope.search = search;
    }


  }
});

UPDATE

To make use of the keyword in controller - just store it as a value.

app.controller('MainCtrl', function($scope, searchVal) {
  $scope.search = searchVal;
});

app.value("searchVal", {
  keyword : "I am in controller - no problem!"
})

app.directive("searchDir", function(searchVal){

  return {

    restrict : "EA",

    scope: {},

    template : '<input \
            style="width:80%" \
            ng-model="search.keyword" \
            size="70" \
            type="search" \
            results="5" \
            placeholder="symptôme, maladie, etc." \
        />',

    link : function(scope, element, attrs){
      scope.search = searchVal;
    }

  }

});

Upvotes: 1

Related Questions